This commit is contained in:
romkazvo
2023-08-07 19:29:24 +08:00
commit 34d6c5d489
4832 changed files with 1389451 additions and 0 deletions

1007
CryGame/AIHandler.cpp Normal file

File diff suppressed because it is too large Load Diff

79
CryGame/AIHandler.h Normal file
View File

@@ -0,0 +1,79 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include <IAgent.h>
#include <ILipSync.h>
struct IScriptSystem;
class CAIHandler : public IDialogLoadSink
{
public:
CAIHandler(void);
~CAIHandler(void);
void Init(CXGame *pGame, IEntity *pEntity, ILog *pLog);
void AIMind( SOBJECTSTATE *state );
void AISignal( int signalID, const char * signalText, IEntity *pSender );
void Release();
void DoReadibilityPack( const char* text );
protected:
IScriptSystem* m_pScriptSystem;
IScriptObject* m_pScriptObject;
IEntity *m_pEntity;
CXGame *m_pGame;
ILog *m_pLog;
IScriptObject *m_pSoundPackTable;
IScriptObject *m_pAnimationPackTable;
string m_NextBehaviorName;
string m_CurrentBehaviorName;
string m_DefaultBehaviorName;
char m_szSignalName[1024];
int m_DamageGrenadeType;
void Release( IScriptObject **obj );
bool CheckCharacter( const char* signalText );
void DoChangeBehavior( );
// void CallScript( IScriptObject *scriptSelf, HSCRIPTFUNCTION functionToCall, float *value=NULL, IEntity *pSender=NULL );
bool CallScript( IScriptObject *scriptTable, const char* funcName, float *value=NULL, IEntity *pSender=NULL );
void CallBehaviorOrDefault( const char* signalText, float *value=NULL,bool bJob = true );
IScriptObject *GetMostLikelyTable( IScriptObject* table);
IScriptObject *FindOrLoadTable( IScriptObject * table, const char* nameToGet );
public:
void SetCurrentBehaviourVariable(const char * szVariableName, float fValue);
void OnDialogLoaded(struct ILipSync *pLipSync);
void OnDialogFailed(struct ILipSync *pLipSync);
IScriptObject *m_pCharacter;
IScriptObject *m_pDefaultCharacter;
IScriptObject *m_pBehavior;
IScriptObject *m_pPreviousBehavior;
IScriptObject *m_pDefaultBehavior;
IScriptObject *m_pDEFAULTDefaultBehavior;
IScriptObject *m_pBehaviorTable;
IScriptObject *m_pBehaviorTableAVAILABLE;
IScriptObject *m_pBehaviorTableINTERNAL;
string m_FirstBehaviorName;
void SetBehaviour( char *szBehaviourName) { m_NextBehaviorName = szBehaviourName; DoChangeBehavior();}
};

126
CryGame/ASEQuerySDK.h Normal file
View File

@@ -0,0 +1,126 @@
/*
ASE Query & Reporting SDK Copyright (C) 2003 UDP Soft Ltd
http://www.udpsoft.com/eye/ All Rights Reserved
Enables reporting to the ASE master server and responding to server
browser queries.
Before reading further, see example.c for a quick display of how simple this
really is.
A quick run-down of things to do:
1. Initialization
extern int ASEQuery_initialize(int hostport, int internet, char *address);
hostport = the join port for the server
internet = flag indicating whether we should report to the ASE master server
(LAN servers should set this to 0)
address = IP address to bind to (pass as NULL if your game does not have
support for multihomed hosts)
This function should be called when the server is started. Does a DNS lookup,
so call only when net already running. NOTE! Winsock must be initialized
before calling the init function (see example.c).
Returns 0 on error, char *ASEQuery_error contains the error message.
2. The worker function
extern int ASEQuery_check(void);
Ideally this should be called every millisecond. The simplest implementation
would be to call this every "frame". Longer delays cause bigger ping
fluctuations ie. not so accurate pings in the server browser.
Returns 0 on error, char *ASEQuery_error contains the error message.
3. Functions that the _game_ has to implement
void ASEQuery_wantstatus(void);
void ASEQuery_wantrules(void);
void ASEQuery_wantplayers(void);
These are called when the SDK needs information about the game state.
In each of these functions, the game must call back to the SDK providing
the required information.
4. Functions that the game calls to provide information back to the SDK
extern void ASEQuery_status(const char *hostname, const char *gametype, const char *mapname, const char *gamever, int password, int numplayers, int maxplayers);
extern void ASEQuery_addrule(const char *key, const char *value);
extern void ASEQuery_addplayer(const char *name, const char *team, const char *skin, const char *score, const char *ping, const char *time);
These can only be called in the corresponding functions described earlier.
ASEQuery_status must only be called once. ASEQuery_addrule and
ASEQuery_addplayer should be called for each rule/player that the game
wishes to be visible in the server browser. Player info fields that don't
apply can be passed as NULL.
5. Shutting down
extern void ASEQuery_shutdown(void);
6. How to link
In C:
#include "ASEQuerySDK.h" in every module that uses the SDK.
In C++:
extern "C" {
#include "ASEQuerySDK.h"
}
Link with ASEQuerySDK.LIB
The SDK uses the __cdecl calling convention.
7. Used ports
The SDK uses gameport+123 (UDP) as the default port for queries. If that port
is not available, the next available port is used (+124, +125...). This port
must have unrestricted access to/from the internet.
8. Other stuff
For ASE support, your game also has to implement commandline parsing for
server address, player name, password etc.
The standard implementation would be:
game.exe +connect ip:port +name "my name" +config "myconfig.cfg" +password "server password"
Let us know the commandline options for your game so we can update ASE
accordingly. In addition to this we'll need the executable name and the
registry key for the install folder.
For the demo version of the SDK, there's built-in ASE support already. Just
go to View -> Options -> Games -> Not Installed -> SDK test and check
"Visible in filter list". Any server running the demo SDK will now appear
under the "SDK test" filter.
actual .h stuff follows
*/
extern int ASEQuery_initialize(int hostport, int internet, char *address);
extern void ASEQuery_shutdown(void);
extern int ASEQuery_check(void);
void ASEQuery_wantstatus(void);
void ASEQuery_wantrules(void);
void ASEQuery_wantplayers(void);
extern void ASEQuery_status(const char *hostname, const char *gametype, const char *mapname, const char *gamever, int password, int numplayers, int maxplayers);
extern void ASEQuery_addrule(const char *key, const char *value);
extern void ASEQuery_addplayer(const char *name, const char *team, const char *skin, const char *score, const char *ping, const char *time);
extern char *ASEQuery_error;

BIN
CryGame/ASEQuerySDK.lib Normal file

Binary file not shown.

504
CryGame/AdvCamSystem.cpp Normal file
View File

@@ -0,0 +1,504 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <IEntitySystem.h>
#include "Game.h"
#include "AdvCamSystem.h" // CAdvCamSystem
#include "XPlayer.h" // CPlayer
#include "Cry_Math.h" // TMatrix_tpl
#include "XEntityProcessingCmd.h" // CXEntityProcessingCmd for ProcessKeys
CAdvCamSystem::CAdvCamSystem(CXGame *pGame)
{
m_pScriptObject=NULL;
m_pGame=pGame;
m_eiPlayerA=INVALID_WID;
m_eiPlayerB=INVALID_WID;
}
//////////////////////////////////////////////////////////////////////////
// Initialize the AdvCamSystem-container.
bool CAdvCamSystem::Init()
{
IEntity *entity = GetEntity();
entity->GetScriptObject()->SetValue("type", "advcamsystem");
// set camera
entity->SetCamera(m_pGame->GetSystem()->GetIEntitySystem()->CreateEntityCamera());
entity->GetCamera()->GetCamera().Init(m_pGame->GetSystem()->GetIRenderer()->GetWidth(),m_pGame->GetSystem()->GetIRenderer()->GetHeight());
entity->SetNeedUpdate(true);
return true;
}
//////////////////////////////////////////////////////////////////////////
// Update the camera.
void CAdvCamSystem::Update( void )
{
//the server doesn't need to update AdvCamSystem
if(!m_pGame->IsClient())
return;
Vec3 vSrcPos, vDstPos;
Vec3 vSrcPos2, vDstPos2;
if(m_pScriptObject)
{
_SmartScriptObject sm(m_pGame->GetScriptSystem(),true);
_SmartScriptObject current(m_pGame->GetScriptSystem(),true);
_SmartScriptObject future(m_pGame->GetScriptSystem(),true);
// get the current state
int currentState = 0;
int futureState = 0;
float blendFactor = 0;
m_pEntity->GetScriptObject()->GetValue("currentState", currentState);
m_pEntity->GetScriptObject()->GetValue("futureState", futureState);
m_pEntity->GetScriptObject()->GetValue("blendFactor", blendFactor);
m_pEntity->GetScriptObject()->GetValue("states", sm);
sm->GetAt(currentState, current);
sm->GetAt(futureState, future);
CalcCameraVectors(current, vSrcPos, vDstPos);
CalcCameraVectors(future, vSrcPos2, vDstPos2);
vSrcPos = (1.0f - blendFactor) * vSrcPos + blendFactor * vSrcPos2;
vDstPos = (1.0f - blendFactor) * vDstPos + blendFactor * vDstPos2;
float currentRadius;
float futureRadius;
current->GetValue("max_radius", currentRadius);
future->GetValue("max_radius", futureRadius);
m_fMaxRadius = (1.0f - blendFactor) * currentRadius + blendFactor * futureRadius;
current->GetValue("min_radius", currentRadius);
future->GetValue("min_radius", futureRadius);
m_fMinRadius = (1.0f - blendFactor) * currentRadius + blendFactor * futureRadius;
}
Vec3 vDir=vDstPos-vSrcPos;
if (vDir.Length() < m_fMinRadius)
{
vDir.Normalize();
vSrcPos = vDstPos - vDir * m_fMinRadius;
}
Ang3 vAngles=ConvertVectorToCameraAnglesSnap180(vDir);
m_pEntity->SetAngles(vAngles);
m_pEntity->SetPos(vSrcPos);
IEntity *pEntity =GetEntity();
IEntityCamera *pEC =pEntity->GetCamera();
Vec3 v3Angles =pEntity->GetAngles();
if(pEC)
{
pEC->SetAngles(v3Angles);
pEC->SetPos(pEntity->GetPos()); // swing up and down - just for testing
}
}
void CAdvCamSystem::OnSetAngles( const Vec3d &ang )
{
/*if(m_pGame->m_pClient->GetPlayerID()==GetEntity()->GetId() || m_pGame->m_pClient->m_bLocalHost)
m_pGame->m_pClient->m_PlayerProcessingCmd.SetDeltaAngles(ang);*/
}
IScriptObject *CAdvCamSystem::GetScriptObject()
{
return m_pScriptObject;
}
void CAdvCamSystem::SetScriptObject(IScriptObject *object)
{
m_pScriptObject=object;
}
//////////////////////////////////////////////////////////////////////////
// Save upcast.
bool CAdvCamSystem::QueryContainerInterface(ContainerInterfaceType desired_interface, void **ppInterface )
{
if (desired_interface == CIT_IADVCAMSYSTEM)
{
*ppInterface = (void *) this;
return true;
}
else
{
*ppInterface = 0;
return false;
}
}
void CAdvCamSystem::GetEntityDesc( CEntityDesc &desc ) const
{
}
//////////////////////////////////////////////////////////////////////////
// Process input.
void CAdvCamSystem::ProcessKeys( CXEntityProcessingCmd &epc )
{
if(m_eiPlayerA && m_eiPlayerB)
{
// get entities
IEntitySystem *pEntitySystem=m_pGame->m_pSystem->GetIEntitySystem(); assert(pEntitySystem);
IEntity *pEntityA = pEntitySystem->GetEntity(m_eiPlayerA); assert(pEntityA);if(!pEntityA)return;
IEntity *pEntityB = pEntitySystem->GetEntity(m_eiPlayerB); assert(pEntityB);if(!pEntityB)return;
// get player containers of the entities
CPlayer *pPlayerA = NULL;
pEntityA->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void **) &pPlayerA); assert(pPlayerA);
CPlayer *pPlayerB = NULL;
pEntityB->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void **) &pPlayerB); assert(pPlayerB);
// determine which direction we are moving in
// build camera matrix
Vec3 vCamAngles;
Matrix33 matCamera;
vCamAngles = m_pEntity->GetAngles();
matCamera.SetRotationAA(gf_DEGTORAD*vCamAngles.z, Vec3(0,0,1));
Matrix33 matPlayerA;
vCamAngles = pEntityA->GetAngles();
matPlayerA.SetRotationAA(gf_DEGTORAD*vCamAngles.z, Vec3(0,0,1));
Matrix33 matPlayerB;
vCamAngles = pEntityB->GetAngles();
matPlayerB.SetRotationAA(gf_DEGTORAD*vCamAngles.z, Vec3(0,0,1));
// we have to make a copy, because the function is called twice per frame. We modify the actions in the epc, so this
// would cause side effects the second time running through the function.
CXEntityProcessingCmd epcCopyA = epc;
CXEntityProcessingCmd epcCopyB = epc;
_SmartScriptObject sm(m_pGame->GetScriptSystem(),true);
_SmartScriptObject current(m_pGame->GetScriptSystem(),true);
int currentState = 0;
float blendFactor = 0;
m_pEntity->GetScriptObject()->GetValue("currentState", currentState);
m_pEntity->GetScriptObject()->GetValue("states", sm);
sm->GetAt(currentState, current);
bool linked_a;
current->GetValue("linked_a", linked_a);
Vec3 vMoveDirA;
if (linked_a)
vMoveDirA = CalcPlayerMoveDirection(matCamera, 0);
else
vMoveDirA = CalcPlayerMoveDirection(matCamera, 0);
Vec3 vMoveDirB = CalcPlayerMoveDirection(matCamera, 1);
// vector from player A to player B
Vec3 vToB = pEntityB->GetPos()-pEntityA->GetPos();
// if player a is outside the follow radius, we move into the direction of player b
float fDistance = vToB.Length();
if (fDistance > m_fMaxRadius)
{
float weight = (fDistance - m_fMaxRadius)/10.0f;
//vToB.Normalize();
if (GetLengthSquared(vMoveDirB) > 0.01)
{
vMoveDirA += (weight)*vToB;
}
else if (GetLengthSquared(vMoveDirA) > 0.01)
{
vMoveDirB += -(weight)*vToB;
}
}
// get input system
ISystem *pSystem = m_pGame->GetSystem();
IInput *pInput = pSystem->GetIInput();
if (pInput->JoyButtonPressed(7))
{
bool isBlending;
m_pEntity->GetScriptObject()->GetValue("isBlending", isBlending);
if (!isBlending)
{
int currentState;
m_pEntity->GetScriptObject()->GetValue("currentState", currentState);
if (currentState == 8)
{
m_pEntity->GetScriptObject()->SetValue("isBlending", true);
m_pEntity->GetScriptObject()->SetValue("futureState", 9);
}
}
}
if (pInput->JoyButtonPressed(6))
{
bool isBlending;
m_pEntity->GetScriptObject()->GetValue("isBlending", isBlending);
if (!isBlending)
{
int currentState;
m_pEntity->GetScriptObject()->GetValue("currentState", currentState);
if (currentState == 8)
{
m_pEntity->GetScriptObject()->SetValue("isBlending", true);
m_pEntity->GetScriptObject()->SetValue("futureState", 10);
}
}
}
if (!pInput->JoyButtonPressed(6) && !pInput->JoyButtonPressed(7))
{
bool isBlending;
m_pEntity->GetScriptObject()->GetValue("isBlending", isBlending);
if (!isBlending)
{
int currentState;
m_pEntity->GetScriptObject()->GetValue("currentState", currentState);
if (currentState != 8)
{
m_pEntity->GetScriptObject()->SetValue("isBlending", true);
m_pEntity->GetScriptObject()->SetValue("futureState", 8);
}
}
}
// hack begin
m_pGame->m_pClient->SetPlayerID(pPlayerA->GetEntity()->GetId());
if (GetLengthSquared(vMoveDirA) > 1.0f)
vMoveDirA.Normalize();
m_pGame->m_pSystem->GetIScriptSystem()->SetGlobalValue("p_speed_run", vMoveDirA.Length()*5.0f);
// hack end
SetMoveDirection(*pPlayerA, *pEntityA, epcCopyA, vMoveDirA, linked_a);
// hack begin
m_pGame->m_pClient->SetPlayerID(pPlayerB->GetEntity()->GetId());
if (GetLengthSquared(vMoveDirB) > 1.0f)
vMoveDirB.Normalize();
m_pGame->m_pSystem->GetIScriptSystem()->SetGlobalValue("p_speed_run", vMoveDirB.Length()*5.0f);
// hack end
SetMoveDirection(*pPlayerB, *pEntityB, epcCopyB, vMoveDirB, true);
// hack
m_pGame->m_pClient->SetPlayerID(GetEntity()->GetId());
}
}
bool CAdvCamSystem::Write(CStream &stm,EntityCloneState *cs)
{
if(!stm.Write(m_eiPlayerA)) return false;
if(!stm.Write(m_eiPlayerB)) return false;
return true;
}
bool CAdvCamSystem::Read(CStream &stm)
{
if(!stm.Read(m_eiPlayerA)) return false;
if(!stm.Read(m_eiPlayerB)) return false;
return true;
}
void CAdvCamSystem::SetMinRadius(float radius)
{
m_fMinRadius = radius;
}
void CAdvCamSystem::SetMaxRadius(float radius)
{
m_fMaxRadius = radius;
}
Vec3 CAdvCamSystem::CalcPlayerMoveDirection(const Matrix33 &matCamera, unsigned int joyID) const
{
Vec3 vMoveDir;
vMoveDir.Set(0,0,0);
// get input system
ISystem *pSystem = m_pGame->GetSystem();
assert(pSystem); if (!pSystem) return vMoveDir;
IInput *pInput = pSystem->GetIInput();
assert(pInput); if (!pInput) return vMoveDir;
Vec3 vControllerDir = (pInput)->JoyGetAnalog1Dir(joyID);
vMoveDir.x = vControllerDir.y * matCamera(0, 1) - vControllerDir.x * matCamera(0,0);
vMoveDir.y = vControllerDir.y * matCamera(1, 1) - vControllerDir.x * matCamera(1,0);
return vMoveDir;
}
void CAdvCamSystem::CalcCameraVectors(_SmartScriptObject &scriptObject, Vec3& vSrcPos, Vec3& vDstPos)
{
CScriptObjectVector oVec(m_pGame->GetScriptSystem(),true);
Vec3 src_a_offset(0, 0, 0);
float src_origin = 0.0f;
Vec3 src_b_offset(0, 0, 0);
Vec3 src_ab_offset_m(0, 0, 0);
Vec3 src_ab_offset_fac(0, 0, 0);
Vec3 dst_a_offset(0, 0, 0);
float dst_origin = 1.0f;
Vec3 dst_b_offset(0, 0, 0);
Vec3 dst_ab_offset_m(0, 0, 0);
Vec3 dst_ab_offset_fac(0, 0, 0);
#define GETVAL(Name) { scriptObject->GetValue(#Name,Name); }
#define GETVEC(Name) { if(scriptObject->GetValue(#Name,*oVec))Name=oVec.Get(); }
GETVEC(src_a_offset)
GETVAL(src_origin)
GETVEC(src_b_offset)
GETVEC(src_ab_offset_m)
GETVEC(src_ab_offset_fac)
GETVEC(dst_a_offset)
GETVAL(dst_origin)
GETVEC(dst_b_offset)
GETVEC(dst_ab_offset_m)
GETVEC(dst_ab_offset_fac)
vSrcPos.Set(0, 0, 0);
vDstPos.Set(0, 0, 0);
Vec3 vA(0,0,0),vB(0,0,0);
Matrix33 baseA_m, baseB_m, baseAB_m, baseAB_fac;
baseA_m.SetIdentity(); baseB_m.SetIdentity(); baseAB_m.SetIdentity(); baseAB_fac.SetIdentity();
if(m_eiPlayerA)
{
IEntitySystem *pEntitySystem=m_pGame->m_pSystem->GetIEntitySystem(); assert(pEntitySystem);
IEntity *pEntity=pEntitySystem->GetEntity(m_eiPlayerA); assert(pEntity);if(!pEntity)return;
vA=pEntity->GetPos();
Ang3 vAnglesA=pEntity->GetAngles();
baseA_m.SetRotationAA(gf_DEGTORAD*vAnglesA.z,Vec3(0,0,1));
}
if(m_eiPlayerB)
{
IEntitySystem *pEntitySystem=m_pGame->m_pSystem->GetIEntitySystem(); assert(pEntitySystem);
IEntity *pEntity=pEntitySystem->GetEntity(m_eiPlayerB); assert(pEntity);if(!pEntity)return;
vB=pEntity->GetPos();
Ang3 vAnglesB=pEntity->GetAngles();
baseB_m.SetRotationAA(gf_DEGTORAD*vAnglesB.z,Vec3(0,0,1));
}
{
Vec3 vA2B=vB-vA;
Vec3 vCross=vA2B^Vec3(0.0f,0.0f,1.0f);
baseAB_fac(0,0)=vCross.x;
baseAB_fac(1,0)=vCross.y;
baseAB_fac(2,0)=vCross.z;
baseAB_fac(0,1)=vA2B.x;
baseAB_fac(1,1)=vA2B.y;
baseAB_fac(2,1)=vA2B.z;
baseAB_fac(0,2)=0.0f;
baseAB_fac(1,2)=0.0f;
baseAB_fac(2,2)=1.0f;
}
{
Vec3 vA2B=vB-vA; vA2B.Normalize();
Vec3 vCross=vA2B^Vec3(0.0f,0.0f,1.0f);
baseAB_m(0,0)=vCross.x;
baseAB_m(1,0)=vCross.y;
baseAB_m(2,0)=vCross.z;
baseAB_m(0,1)=vA2B.x;
baseAB_m(1,1)=vA2B.y;
baseAB_m(2,1)=vA2B.z;
baseAB_m(0,2)=0.0f;
baseAB_m(1,2)=0.0f;
baseAB_m(2,2)=1.0f;
}
vSrcPos+= vB*src_origin+vA*(1.0f-src_origin);
vSrcPos+= baseA_m*src_a_offset;
vSrcPos+= baseB_m*src_b_offset;
vSrcPos+= baseAB_m*src_ab_offset_m;
vSrcPos+= baseAB_fac*src_ab_offset_fac;
vDstPos += vB*dst_origin+vA*(1.0f-dst_origin);
vDstPos += baseA_m*dst_a_offset;
vDstPos += baseB_m*dst_b_offset;
vDstPos += baseAB_m*dst_ab_offset_m;
vDstPos += baseAB_fac*dst_ab_offset_fac;
}
void CAdvCamSystem::SetMoveDirection(CPlayer &player, const IEntity &entity, CXEntityProcessingCmd &epc, const Vec3 &vMoveDir, bool linked) const
{
// we always move forward, so clear the processing command
epc.Reset();
if (linked)
{
if (GetLengthSquared(vMoveDir) > 0.01f)
{
Ang3 vAngles;
epc.AddAction(ACTION_MOVE_FORWARD);
vAngles=ConvertVectorToCameraAnglesSnap180(vMoveDir);
epc.SetDeltaAngles(Vec3(0, 0, vAngles.z));
}
else
{
epc.SetDeltaAngles(entity.GetAngles());
}
}
else
{
// get direction from other controller
ISystem *pSystem = m_pGame->GetSystem();
IInput *pInput = pSystem->GetIInput();
Vec3 vMoveDir2 = pInput->JoyGetAnalog1Dir(0);
if (GetLengthSquared(vMoveDir2) > 0.01f)
{
if (vMoveDir2.y < -0.1f)
epc.AddAction(ACTION_MOVE_FORWARD);
else if (vMoveDir2.y > 0.1f)
epc.AddAction(ACTION_MOVE_BACKWARD);
}
Vec3 vControllerDir = pInput->JoyGetAnalog2Dir(0);
Ang3 vAngles = entity.GetAngles();
if (fabs(vMoveDir2.x) > 0.1)
vAngles.z -= vMoveDir2.x*4.0f;
epc.SetDeltaAngles(Vec3(0, 0, vAngles.z));
}
player.ProcessCmd(0, epc); // first parameter is not used
player.ProcessAngles(epc);
}

89
CryGame/AdvCamSystem.h Normal file
View File

@@ -0,0 +1,89 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// History:
// 02/12/2002 * created by M.M. (modified version of CSpectator)
//
//////////////////////////////////////////////////////////////////////
#ifndef _ADVCAMSYSTEM_H_
#define _ADVCAMSYSTEM_H_
#include "GameObject.h"
#include <IEntitySystem.h>
class CXGame;
/*!implements the AdvancedCameraSystem container
*/
class CAdvCamSystem : public CGameObject
{
public:
//! constructor
CAdvCamSystem( CXGame *pGame );
//! destructor
virtual ~CAdvCamSystem( void ) {}
//! process input
void ProcessKeys( CXEntityProcessingCmd &epc );
// interface IEntityContainer -------------------------------
virtual bool Init( void );
virtual void Update( void );
virtual bool Write( CStream &stm, EntityCloneState *cs=NULL );
virtual bool Read( CStream &stm );
virtual IScriptObject *GetScriptObject( void );
virtual void SetScriptObject(IScriptObject *object);
virtual void OnSetAngles( const Vec3 &ang );
virtual void OnDraw( const SRendParams & RendParams ) {}
virtual bool QueryContainerInterface( ContainerInterfaceType desired_interface, void **pInterface);
virtual void GetEntityDesc( CEntityDesc &desc ) const;
//! Set the radius at which player a will follow player b
void SetMaxRadius(float radius);
//! Set the minimum distance the players can be together
void SetMinRadius(float radius);
private:
/*! Calculate the movement of a player based on the input received by the specified controller.
@param matCamera orientation of camera
@param joyID number of joystick used for player input
@param linked
@return movement direction of the player (not normalized)
*/
Vec3 CalcPlayerMoveDirection(const Matrix33 &matCamera, unsigned int joyID) const;
/*! Calculate the source and target vectors of the camera based on the script-side parameter table, which is passed
to the function via the script object.
@param scriptObject ScriptObject which contains the parameters for the camera setup (see AdvCamSystem.lua)
@param vSrcPos the source vector returned by the function (reset to zero vector internally)
@param vDstPos the target vector returned by the function (reset to zero vector internally)
*/
void CalcCameraVectors(_SmartScriptObject &scriptObject, Vec3& vSrcPos, Vec3& vDstPos);
void SetMoveDirection(CPlayer &player, const IEntity &entity, CXEntityProcessingCmd &epc, const Vec3 &vMoveDir, bool linked) const;
void PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime) {};
private:
IScriptObject * m_pScriptObject; //!< to fulfull the IEntityContainer interface
CXGame * m_pGame; //!< pointer to the game where we are, must not be 0
EntityId m_eiPlayerA; //!< entity id for player a, may be 0=not assigned
EntityId m_eiPlayerB; //!< entity id for player b, may be 0=not assigned
float m_fMaxRadius; //!< Radius at which player A will start following player B, default 5, must be positive
float m_fMinRadius; //!< Player A and Player B can not get closer than this
friend class CScriptObjectAdvCamSystem;
};
#endif // _ADVCAMSYSTEM_H_

224
CryGame/BitStream_Base.cpp Normal file
View File

@@ -0,0 +1,224 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "bitstream_base.h"
CBitStream_Base::CBitStream_Base()
{
}
CBitStream_Base::~CBitStream_Base()
{
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const int8 Value, const eBitStreamHint eHint )
{
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, int8 &Value, const eBitStreamHint eHint )
{
return stm.Read((char&)Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const int16 Value, const eBitStreamHint eHint )
{
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, int16 &Value, const eBitStreamHint eHint )
{
return stm.Read(Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const int32 Value, const eBitStreamHint eHint )
{
return stm.Write((unsigned int)Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, int32 &Value, const eBitStreamHint eHint )
{
return stm.Read((int&)Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const uint8 Value, const eBitStreamHint eHint )
{
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, uint8 &Value, const eBitStreamHint eHint )
{
return stm.Read(Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const uint16 Value, const eBitStreamHint eHint )
{
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, uint16 &Value, const eBitStreamHint eHint )
{
return stm.Read(Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const uint32 Value, const eBitStreamHint eHint )
{
return stm.Write((unsigned int)Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, uint32 &Value, const eBitStreamHint eHint )
{
return stm.Read((unsigned int&)Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const float Value, const eBitStreamHint eHint )
{
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, float &Value, const eBitStreamHint eHint )
{
return stm.Read(Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const Vec3 &Value, const eBitStreamHint eHint )
{
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, Vec3 &Value, const eBitStreamHint eHint )
{
return stm.Read(Value);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
bool CBitStream_Base::WriteBitStream( CStream &stm, const char *Value, const DWORD nBufferSize, const eBitStreamHint eHint )
{
assert(strlen(Value)<nBufferSize);
return stm.Write(Value);
}
bool CBitStream_Base::ReadBitStream( CStream &stm, char *Value, const DWORD nBufferSize, const eBitStreamHint eHint )
{
return stm.Read(Value,nBufferSize);
}
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------
void CBitStream_Base::SimulateWriteRead( int8 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( int16 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( int32 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( uint8 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( uint16 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( uint32 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( float &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( Vec3 &Value, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,eHint);
ReadBitStream(stm,Value,eHint);
}
void CBitStream_Base::SimulateWriteRead( char *Value, const DWORD nBufferSize, const eBitStreamHint eHint )
{
CStream stm;
WriteBitStream(stm,Value,nBufferSize,eHint);
ReadBitStream(stm,Value,nBufferSize,eHint);
}

54
CryGame/BitStream_Base.h Normal file
View File

@@ -0,0 +1,54 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef BITSTREAM_BASE_H
#define BITSTREAM_BASE_H
#include "ibitstream.h"
class CBitStream_Base :public IBitStream
{
public:
CBitStream_Base();
virtual ~CBitStream_Base();
// interface IBitSubStream -----------------------------------------------
virtual bool WriteBitStream( CStream &stm, const int8 Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const int16 Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const int32 Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const uint8 Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const uint16 Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const uint32 Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const float Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const Vec3 &Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const char *Value, const DWORD nBufferSize, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, int8 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, int16 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, int32 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, uint8 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, uint16 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, uint32 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, float &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, Vec3 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, char *Value, const DWORD nBufferSize, const eBitStreamHint eHint );
virtual void SimulateWriteRead( int8 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( int16 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( int32 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( uint8 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( uint16 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( uint32 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( float &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( Vec3 &Value, const eBitStreamHint eHint );
virtual void SimulateWriteRead( char *Value, const DWORD nBufferSize, const eBitStreamHint eHint );
};
#endif // BITSTREAM_BASE_H

View File

@@ -0,0 +1,265 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "bitstream_compressed.h"
static const DWORD g_dwBits=16; // higher quality angles
//////////////////////////////////////////////////////////////////////////
CBitStream_Compressed::CBitStream_Compressed()
{
}
//////////////////////////////////////////////////////////////////////////
CBitStream_Compressed::~CBitStream_Compressed()
{
}
//////////////////////////////////////////////////////////////////////////
bool CBitStream_Compressed::WriteBitStream( CStream &stm, const uint32 Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eEntityId:
{
WORD word=(WORD)Value;
if(!stm.WritePkd((int16)word)) // compressed as signed number because negative EntityId are dynamic
return false;
}
return true;
case eEntityClassId:
return stm.WritePkd((uint16)Value);
}
return stm.Write((unsigned int)Value);
}
bool CBitStream_Compressed::ReadBitStream( CStream &stm, uint32 &Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eEntityId:
{
int16 Val;
if(!stm.ReadPkd(Val)) // compressed as signed number because negative EntityId are dynamic
return false;
uint16 wVal=(uint16)Val;
Value=(uint32)wVal;
}
return true;
case eEntityClassId:
{
uint16 Val;
if(!stm.ReadPkd(Val))
return false;
Value=(int32)Val;
}
return true;
}
return stm.Read((unsigned int&)Value);
}
bool CBitStream_Compressed::WriteBitStream( CStream &stm, const int32 Value, const eBitStreamHint eHint )
{
return WriteBitStream(stm,(uint32)Value,eHint);
}
bool CBitStream_Compressed::ReadBitStream( CStream &stm, int32 &Value, const eBitStreamHint eHint )
{
return ReadBitStream(stm,(uint32 &)Value,eHint);
}
bool CBitStream_Compressed::WriteBitStream( CStream &stm, const float Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eSignedUnitValueLQ:
{
assert(Value>=-1.0 && Value<=1.0); // check valid range
if(!stm.Write(Value!=0))
return false;
if(Value!=0) // can be done better
{
if(!stm.Write(Value>0)) //sign
return false;
if(!stm.Write(((BYTE)(fabs(Value)/(1.0f/255)))))
return false;
}
}
return true;
default:
return stm.Write(Value);
}
}
bool CBitStream_Compressed::ReadBitStream( CStream &stm, float &Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eSignedUnitValueLQ:
{
bool bNotZero;
if(!stm.Read(bNotZero))
return false;
if(bNotZero)
{
bool sign;
BYTE lean;
if(!stm.Read(sign))
return false;
if(!stm.Read(lean))
return false;
Value=sign?(lean*(1.0f/255)):-(lean*(1.0f/255));
}
else Value=0.0f;
}
return true;
default:
return stm.Read(Value);
}
}
bool CBitStream_Compressed::WriteBitStream( CStream &stm, const Vec3 &Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eEulerAnglesHQ:
{
const float fScale=(1<<g_dwBits)/360.0f;
DWORD X=(DWORD)(Value.x*fScale+0.5f); // convert
DWORD Y=(DWORD)(Value.y*fScale+0.5f);
DWORD Z=(DWORD)(Value.z*fScale+0.5f);
DWORD dwX=(X)&((1<<g_dwBits)-1); // mask
DWORD dwY=(Y)&((1<<g_dwBits)-1);
DWORD dwZ=(Z)&((1<<g_dwBits)-1);
if(!stm.WriteNumberInBits((unsigned int) dwX,g_dwBits))
return false;
if(dwY==0)
{
if(!stm.Write(false)) // bNotZero
return false;
}
else
{
if(!stm.Write(true)) // bNotZero
return false;
if(!stm.WriteNumberInBits((unsigned int) dwY,g_dwBits))
return false;
}
if(!stm.WriteNumberInBits((unsigned int) dwZ,g_dwBits))
return false;
}
return true;
default:
return stm.Write(Value);
}
}
bool CBitStream_Compressed::ReadBitStream( CStream &stm, Vec3 &Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eEulerAnglesHQ:
{
const float fScale=360.0f/(1<<g_dwBits);
DWORD dwX,dwY,dwZ;
if(!stm.ReadNumberInBits((unsigned int&) dwX,g_dwBits))
return false;
bool bNotZero;
if(!stm.Read(bNotZero))
return false;
if(bNotZero)
{
if(!stm.ReadNumberInBits((unsigned int&) dwY,g_dwBits))
return false;
}
else dwY=0;
if(!stm.ReadNumberInBits((unsigned int&) dwZ,g_dwBits))
return false;
Value = Vec3(((float)dwX-0.5f)*fScale,((float)dwY-0.5f)*fScale,((float)dwZ-0.5f)*fScale); // convert
return true;
}
break;
default:
return stm.Read(Value);
}
}
bool CBitStream_Compressed::WriteBitStream( CStream &stm, const uint16 Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eEntityId:
{
WORD word=(WORD)Value;
if(!stm.WritePkd((int16)word)) // compressed as signed number because negative EntityId are dynamic
return false;
}
return true;
case eEntityClassId:
return stm.WritePkd((uint16)Value);
}
return stm.Write(Value);
}
bool CBitStream_Compressed::ReadBitStream( CStream &stm, uint16 &Value, const eBitStreamHint eHint )
{
switch(eHint)
{
case eEntityId:
{
int16 Val;
if(!stm.ReadPkd(Val)) // compressed as signed number because negative EntityId are dynamic
return false;
Value=(uint16)Val;
}
return true;
case eEntityClassId:
{
uint16 Val;
if(!stm.ReadPkd(Val))
return false;
Value=(int16)Val;
}
return true;
}
return stm.Read(Value);
}

View File

@@ -0,0 +1,41 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef BITSTREAM_COMPRESSED_H
#define BITSTREAM_COMPRESSED_H
#include "bitstream_base.h" // CBitStream_Base
class CBitStream_Compressed :public CBitStream_Base
{
public:
//! constructor
CBitStream_Compressed();
//! destructor
virtual ~CBitStream_Compressed();
// interface IBitSubStream -----------------------------------------------
virtual bool WriteBitStream( CStream &stm, const uint32 Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, uint32 &Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const int32 Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, int32 &Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const float Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, float &Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const Vec3 &Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, Vec3 &Value, const eBitStreamHint eHint );
virtual bool WriteBitStream( CStream &stm, const uint16 Value, const eBitStreamHint eHint );
virtual bool ReadBitStream( CStream &stm, uint16 &Value, const eBitStreamHint eHint );
};
#endif // BITSTREAM_COMPRESSED_H

435
CryGame/BugsFlock.cpp Normal file
View File

@@ -0,0 +1,435 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: bugsflock.cpp
// Version: v1.00
// Created: 11/4/2003 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "BugsFlock.h"
#include <CryCharAnimationParams.h>
#define BUGS_SCARE_DISTANCE 3.0f
enum EBugsFlockBehaviors
{
EBUGS_BUG,
EBUGS_DRAGONFLY,
EBUGS_FROG,
};
//! Return random value in [-1,1] range.
inline float frand()
{
return ((float)rand()*2.0f / RAND_MAX) - 1.0f;
}
//////////////////////////////////////////////////////////////////////////
CBugsFlock::CBugsFlock( int id,CFlockManager *flockMgr )
: CFlock( id,flockMgr )
{
}
//////////////////////////////////////////////////////////////////////////
CBugsFlock::~CBugsFlock()
{
ReleaseObjects();
}
void CBugsFlock::ReleaseObjects()
{
for (unsigned int i = 0; i < m_objects.size(); i++)
{
if (m_objects[i])
m_bc.engine->ReleaseObject( m_objects[i] );
}
m_objects.clear();
}
//////////////////////////////////////////////////////////////////////////
void CBugsFlock::CreateBoids( SBoidsCreateContext &ctx )
{
int i;
ClearBoids();
ReleaseObjects();
AABB bbox;
bbox.min.Set(0,0,0);
bbox.max.Set(0,0,0);
for (i = 0; i < (int)ctx.models.size(); i++)
{
IStatObj *pObj = m_bc.engine->MakeObject( ctx.models[i].c_str() );
if (pObj)
{
bbox.Add( pObj->GetBoxMin() );
bbox.Add( pObj->GetBoxMax() );
m_objects.push_back( pObj );
}
}
int numObj = m_objects.size();
// Different boids.
for (i = 0; i < ctx.boidsCount; i++)
{
CBoidBug *boid = new CBoidBug( m_bc );
float radius = m_bc.MaxAttractDistance;
boid->m_pos = m_origin + Vec3(radius*frand(),radius*frand(),
m_bc.MinHeight+(m_bc.MaxHeight-m_bc.MinHeight)*frand() );
boid->m_heading = GetNormalized( Vec3(frand(),frand(),0) );
boid->m_speed = m_bc.MinSpeed + (m_bc.MaxSpeed-m_bc.MinSpeed)*frand();
//boid->CalcRandomTarget( GetPos(),m_bc );
if (!ctx.characterModel.empty())
{
if (numObj == 0 || (i % (numObj+1) == 0))
{
boid->m_object = m_flockMgr->GetSystem()->GetIAnimationSystem()->MakeCharacter( ctx.characterModel.c_str() );
if (boid->m_object)
{
Vec3 mins,maxs;
boid->m_object->GetBBox(mins,maxs);
bbox.Add( mins );
bbox.Add( maxs );
if (!ctx.animation.empty())
{
// Play animation in loop.
boid->m_object->StartAnimation( ctx.animation.c_str(), CryCharAnimationParams() );
ICryAnimationSet *animSet = boid->m_object->GetModel()->GetAnimationSet();
if (animSet)
{
animSet->SetLoop( animSet->Find(ctx.animation.c_str()),true );
}
}
}
}
}
if (numObj > 0)
boid->m_objectId = (i % numObj);
else
boid->m_objectId = 0;
//boid->m_p = m_flockMgr->GetSystem()->GetI3DEngine()->MakeCharacter( model.c_str() );
/*
if (boid->m_object)
{
boid->Physicalize(m_bc);
}
*/
AddBoid(boid);
}
m_bc.fBoidRadius = GetLength(bbox.max - bbox.min) * m_bc.boidScale;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CBoidBug::CBoidBug( SBoidContext &bc )
: CBoidObject( bc )
{
m_objectId = 0;
m_onGround = 0;
}
void CBoidBug::UpdateBugsBehavior( float dt,SBoidContext &bc )
{
if ((rand() % 10) == 0)
{
// Randomally modify heading vector.
m_heading.x += frand()*0.2f*bc.factorAlignment; // Used as random movement.
m_heading.y += frand()*0.2f*bc.factorAlignment;
m_heading.z += frand()*0.1f*bc.factorAlignment;
m_heading = GetNormalized(m_heading);
if (bc.behavior == EBUGS_DRAGONFLY)
m_speed = bc.MinSpeed + (bc.MaxSpeed - bc.MinSpeed)*frand();
}
// Avoid player.
Vec3 fromPlayerVec = Vec3( m_pos.x-bc.playerPos.x, m_pos.y-bc.playerPos.y, 0 );
if (GetLengthSquared(fromPlayerVec) < BUGS_SCARE_DISTANCE*BUGS_SCARE_DISTANCE) // 2 meters.
{
float d = (BUGS_SCARE_DISTANCE - fromPlayerVec.Length());
m_accel += 5.0f * fromPlayerVec * d;
}
// Maintain average speed.
float targetSpeed = (bc.MaxSpeed + bc.MinSpeed)/2;
m_accel -= m_heading*(m_speed-targetSpeed)*0.5f;
//m_accel = (m_targetPos - m_pos)*bc.factorAttractToOrigin;
if (m_pos.z < bc.terrainZ+bc.MinHeight)
{
m_accel.z = (bc.terrainZ+bc.MinHeight-m_pos.z)*bc.factorAttractToOrigin;
}
else if (m_pos.z > bc.terrainZ+bc.MaxHeight)
{
m_accel.z = -(m_pos.z-bc.terrainZ+bc.MinHeight)*bc.factorAttractToOrigin;
}
else
{
// Allways try to accelerate in direction oposite to current in Z axis.
m_accel.z += -m_heading.z * 0.2f;
}
}
//////////////////////////////////////////////////////////////////////////
void CBoidBug::UpdateDragonflyBehavior( float dt,SBoidContext &bc )
{
UpdateBugsBehavior( dt,bc );
}
//////////////////////////////////////////////////////////////////////////
void CBoidBug::UpdateFrogsBehavior( float dt,SBoidContext &bc )
{
if (m_onGround)
{
if (((rand() % 100) == 1) ||
(GetLengthSquared(Vec3(bc.playerPos.x-m_pos.x,bc.playerPos.y-m_pos.y,0)) < BUGS_SCARE_DISTANCE*BUGS_SCARE_DISTANCE))
{
// Sacred by player or random jump.
m_onGround = false;
m_heading = m_pos - bc.playerPos;
if (m_heading != Vec3(0,0,0))
m_heading = GetNormalized(m_heading);
else
m_heading = GetNormalized(Vec3(frand(),frand(),frand()));
m_heading.z = 0.2f + (frand()+1.0f)*0.5f;
m_heading += Vec3(frand()*0.3f,frand()*0.3f,0 );
if (m_heading != Vec3(0,0,0))
m_heading = GetNormalized(m_heading);
else
m_heading = GetNormalized(Vec3(frand(),frand(),frand()));
m_speed = bc.MaxSpeed;
}
}
bc.terrainZ = bc.engine->GetTerrainElevation(m_pos.x,m_pos.y);
float range = bc.MaxAttractDistance;
Vec3 origin = bc.flockPos;
if (bc.followPlayer)
{
origin = bc.playerPos;
}
// Keep in range.
if (bc.followPlayer)
{
if (m_pos.x < origin.x - range)
m_pos.x = origin.x + range;
if (m_pos.y < origin.y - range)
m_pos.y = origin.y + range;
if (m_pos.x > origin.x + range)
m_pos.x = origin.x - range;
if (m_pos.y > origin.y + range)
m_pos.y = origin.y - range;
}
else
{
/*
if (bc.behavior == EBUGS_BUG || bc.behavior == EBUGS_DRAGONFLY)
{
if (m_pos.x < origin.x-range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
if (m_pos.y < origin.y-range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
if (m_pos.x > origin.x+range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
if (m_pos.y > origin.y+range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
}
*/
}
m_accel.Set( 0,0,-10 );
bool bBanking = m_object != 0;
CalcMovement( dt,bc,bBanking );
if (m_pos.z < bc.terrainZ+0.1f)
{
// Land.
m_pos.z = bc.terrainZ+0.1f;
m_onGround = true;
m_speed = 0;
}
}
//////////////////////////////////////////////////////////////////////////
void CBoidBug::Update( float dt,SBoidContext &bc )
{
if (bc.behavior == EBUGS_FROG)
{
UpdateFrogsBehavior( dt,bc );
return;
}
if (m_onGround)
{
if (GetLengthSquared(Vec3(bc.playerPos.x-m_pos.x,bc.playerPos.y-m_pos.y,0)) < BUGS_SCARE_DISTANCE*BUGS_SCARE_DISTANCE)
{
// Sacred by player, fast takeoff.
m_onGround = false;
m_heading = GetNormalized(m_pos - bc.playerPos);
m_heading.z = 0.3f;
m_heading = GetNormalized(m_heading);
m_speed = 1;
}
else if ((rand() % 50) == 0)
{
// take off.
m_onGround = false;
m_heading.z = 0.2f;
m_heading = GetNormalized(m_heading);
}
return;
}
// Keep in range.
bc.terrainZ = bc.engine->GetTerrainElevation(m_pos.x,m_pos.y);
float range = bc.MaxAttractDistance;
Vec3 origin = bc.flockPos;
if (bc.followPlayer)
{
origin = bc.playerPos;
}
if (bc.followPlayer)
{
if (m_pos.x < origin.x - range)
m_pos.x = origin.x + range;
if (m_pos.y < origin.y - range)
m_pos.y = origin.y + range;
if (m_pos.x > origin.x + range)
m_pos.x = origin.x - range;
if (m_pos.y > origin.y + range)
m_pos.y = origin.y - range;
}
else
{
if (bc.behavior == EBUGS_BUG || bc.behavior == EBUGS_DRAGONFLY)
{
if (m_pos.x < origin.x-range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
if (m_pos.y < origin.y-range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
if (m_pos.x > origin.x+range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
if (m_pos.y > origin.y+range)
m_accel = (origin - m_pos)*bc.factorAttractToOrigin;
}
}
if (bc.behavior == EBUGS_BUG)
{
UpdateBugsBehavior( dt,bc );
}
else if (bc.behavior == EBUGS_DRAGONFLY)
{
UpdateDragonflyBehavior( dt,bc );
}
else if (bc.behavior == EBUGS_FROG)
{
UpdateFrogsBehavior( dt,bc );
}
else
{
UpdateBugsBehavior( dt,bc );
}
bool bBanking = m_object != 0;
CalcMovement( dt,bc,bBanking );
if (m_pos.z < bc.terrainZ+0.1f)
{
// Land.
m_pos.z = bc.terrainZ+0.1f;
if (!bc.noLanding && (rand()%10) == 0)
{
m_onGround = true;
m_speed = 0;
m_accel.Set(0,0,0);
}
}
if (m_pos.z < bc.waterLevel)
m_pos.z = bc.waterLevel;
}
//////////////////////////////////////////////////////////////////////////
void CBoidBug::Render( SRendParams &rp,CCamera &cam,SBoidContext &bc )
{
// Cull boid.
if (!cam.IsSphereVisibleFast( Sphere(m_pos,bc.fBoidRadius*bc.boidScale) ))
return;
Vec3 oldheading;
if (bc.behavior == EBUGS_FROG)
{
// Frogs/grasshopers do not change z orientation.
oldheading = m_heading;
if (fabsf(m_heading.x > 0.0001f) || fabsf(m_heading.y > 0.0001f))
m_heading = GetNormalized( Vec3(m_heading.x,m_heading.y,0 ) );
else
{
m_heading = GetNormalized(Vec3(frand(),frand(),frand()));
oldheading = m_heading;
}
}
Matrix44 mtx;
CalcMatrix( mtx );
mtx.ScaleMatRow( Vec3(bc.boidScale,bc.boidScale,bc.boidScale) );
if (bc.behavior == EBUGS_FROG)
{
m_heading = oldheading;
}
rp.pMatrix = &mtx;
if (m_object)
{
m_object->Update();
m_object->Draw( rp, Vec3(zero) );
}
else
{
//pStatObj
CBugsFlock *flock = (CBugsFlock*)m_flock;
int numo = flock->m_objects.size();
if (numo == 0)
return;
IStatObj *pObj = flock->m_objects[m_objectId % numo];
if (!pObj)
return;
pObj->Render( rp, Vec3(zero),0);
}
}
void CBugsFlock::PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime)
{
for (unsigned int i = 0; i < m_objects.size(); i++)
{
IStatObj * pStatObj = m_objects[i];
float fDistance = fPrevPortalDistance + vPrevPortalPos.GetDistance((m_bounds.min+m_bounds.min)*0.5f);
pStatObj->PreloadResources(fDistance, fTime, 0);
}
}

61
CryGame/BugsFlock.h Normal file
View File

@@ -0,0 +1,61 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: bugsflock.h
// Version: v1.00
// Created: 11/4/2003 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __bugsflock_h__
#define __bugsflock_h__
#pragma once
#include "Flock.h"
/*! Single Bug.
*/
class CBoidBug : public CBoidObject
{
public:
CBoidBug( SBoidContext &bc );
void Update( float dt,SBoidContext &bc );
void Render( SRendParams &rp,CCamera &cam,SBoidContext &bc );
private:
void UpdateBugsBehavior( float dt,SBoidContext &bc );
void UpdateDragonflyBehavior( float dt,SBoidContext &bc );
void UpdateFrogsBehavior( float dt,SBoidContext &bc );
//void CalcRandomTarget( const Vec3 &origin,SBoidContext &bc );
friend class CBugsFlock;
int m_objectId;
//Vec3 m_targetPos;
// Flags.
unsigned m_onGround : 1; //! True if landed on ground.
//unsigned m_landing : 1; //! True if bird wants to land.
//unsigned m_takingoff : 1; //! True if bird is just take-off from land.
};
/*! Bugs Flock, is a specialized flock type for all kind of small bugs and flies around player.
*/
class CBugsFlock : public CFlock
{
public:
CBugsFlock( int id,CFlockManager *flockMgr );
~CBugsFlock();
virtual void CreateBoids( SBoidsCreateContext &ctx );
virtual void PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime);
protected:
void ReleaseObjects();
friend class CBoidBug;
std::vector<IStatObj*> m_objects;
};
#endif // __bugsflock_h__

47
CryGame/CMovieUser.h Normal file
View File

@@ -0,0 +1,47 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef MOVIE_USER_H
#define MOVIE_USER_H
//////////////////////////////////////////////////////////////////////////
// Interface for movie-system implemented by user for advanced function-support
class CMovieUser : public IMovieUser, public ISoundEventListener
{
private:
CXGame *m_pGame;
public:
CMovieUser(CXGame *pGame)
{
m_InCutSceneCounter = 0;
m_wPrevClientId = 0;
m_pGame=pGame;
m_fPrevMusicVolume=0;
}
// interface IMovieUser
void SetActiveCamera(const SCameraParams &Params);
void BeginCutScene(unsigned long dwFlags,bool bResetFX);
void EndCutScene();
void SendGlobalEvent(const char *pszEvent);
void PlaySubtitles( ISound *pSound );
// Implmenents ISoundEventListener.
void OnSoundEvent( ESoundCallbackEvent event,ISound *pSound );
private:
void ResetCutSceneParams();
int m_InCutSceneCounter;
int m_wPrevClientId;
Vec3d m_vPrevClientPos;
bool m_bSoundsPaused;
float m_fPrevMusicVolume;
};
#endif

46
CryGame/CryGame.cpp Normal file
View File

@@ -0,0 +1,46 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
// CryGame.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "CryGame.h"
#ifndef _XBOX
//#if !defined(LINUX)
_ACCESS_POOL;
//#endif//LINUX
#endif //_XBOX
#if !defined(PS2) && !defined(_XBOX) && !defined(LINUX)
// DLL-EntryPoint
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
#ifdef USE_MEM_POOL
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
if(!CHECK_POOL())
return FALSE;
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
#endif
return TRUE;
}
#endif
#include <CrtDebugStats.h>

23
CryGame/CryGame.h Normal file
View File

@@ -0,0 +1,23 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef __crygame_h__
#define __crygame_h__
#pragma once
#ifdef WIN32
#ifdef CRYGAME_EXPORTS
#define CRYGAME_API __declspec(dllexport)
#else
#define CRYGAME_API __declspec(dllimport)
#endif
#else
#define CRYGAME_API
#endif
#endif // __crygame_h__

1039
CryGame/CryGame.vcproj Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = "file:F:\\Crytek\\CryGame\\CryGame.vcproj"
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT"
}

650
CryGame/CryGame_XBox.vcproj Normal file
View File

@@ -0,0 +1,650 @@
<?xml version="1.0" encoding = "windows-1251"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.00"
Name="CryGame_XBox"
ProjectGUID="{A7EC04A5-D65C-4C45-969C-D842823446ED}"
SccProjectName="&quot;$/Game01/CryGame&quot;, FESAAAAA"
SccAuxPath=""
SccLocalPath="."
SccProvider="MSSCCI:Microsoft Visual SourceSafe">
<Platforms>
<Platform
Name="Xbox"/>
</Platforms>
<Configurations>
<Configuration
Name="Debug|Xbox"
OutputDirectory="Debug_XBox"
IntermediateDirectory="Debug_XBox"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="..\CryCommon"
PreprocessorDefinitions="_DEBUG;_XBOX;_LIB"
BasicRuntimeChecks="3"
RuntimeLibrary="5"
BufferSecurityCheck="TRUE"
EnableFunctionLevelLinking="TRUE"
UsePrecompiledHeader="3"
PrecompiledHeaderThrough="stdafx.h"
PrecompiledHeaderFile=".\Debug_XBox/CryGame.pch"
AssemblerListingLocation=".\Debug_XBox/"
ObjectFile=".\Debug_XBox/"
ProgramDataBaseFileName=".\Debug_XBox/"
WarningLevel="3"
SuppressStartupBanner="TRUE"
DebugInformationFormat="4"
CompileAs="0"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/CryGame.lib"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
</Configuration>
<Configuration
Name="Release|Xbox"
OutputDirectory="Release_XBox"
IntermediateDirectory="Release_XBox"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
GlobalOptimizations="TRUE"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="TRUE"
FavorSizeOrSpeed="1"
OmitFramePointers="TRUE"
AdditionalIncludeDirectories="..\CryCommon"
PreprocessorDefinitions="_RELEASE;NDEBUG;_XBOX;_LIB"
StringPooling="TRUE"
RuntimeLibrary="4"
EnableFunctionLevelLinking="TRUE"
UsePrecompiledHeader="3"
PrecompiledHeaderThrough="stdafx.h"
PrecompiledHeaderFile="$(IntDir)/CryGame.pch"
AssemblerListingLocation="$(IntDir)/"
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/"
WarningLevel="3"
SuppressStartupBanner="TRUE"
DebugInformationFormat="2"
CompileAs="0"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/CryGame.lib"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
</Configuration>
<Configuration
Name="Profile|Xbox"
OutputDirectory="Profile"
IntermediateDirectory="Profile"
ConfigurationType="4"
UseOfMFC="0"
ATLMinimizesCRunTimeLibraryUsage="FALSE"
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
Optimization="1"
GlobalOptimizations="TRUE"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="FALSE"
FavorSizeOrSpeed="0"
OmitFramePointers="TRUE"
OptimizeForProcessor="2"
AdditionalIncludeDirectories="..\CryCommon"
PreprocessorDefinitions="NDEBUG;_XBOX;_LIB"
StringPooling="TRUE"
BufferSecurityCheck="FALSE"
DisableLanguageExtensions="FALSE"
ForceConformanceInForLoopScope="FALSE"
UsePrecompiledHeader="3"
PrecompiledHeaderThrough="stdafx.h"
PrecompiledHeaderFile=".\Profile/CryGame.pch"
AssemblerListingLocation=".\Profile/"
ObjectFile=".\Profile/"
ProgramDataBaseFileName=".\Profile/"
WarningLevel="3"
SuppressStartupBanner="TRUE"
DebugInformationFormat="3"
CompileAs="0"/>
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCLibrarianTool"
OutputFile="$(OutDir)/CryGame.lib"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
<Tool
Name="VCPreLinkEventTool"/>
</Configuration>
</Configurations>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat">
<File
RelativePath="AIHandler.cpp">
</File>
<File
RelativePath="AdvCamSystem.cpp">
</File>
<File
RelativePath="BugsFlock.cpp">
</File>
<File
RelativePath=".\CryGame.cpp">
</File>
<File
RelativePath=".\EntityClassRegistry.cpp">
</File>
<File
RelativePath=".\Game.cpp">
</File>
<File
RelativePath=".\GameLoading.cpp">
</File>
<File
RelativePath="GameMemStats.cpp">
</File>
<File
RelativePath=".\IngameDialog.cpp">
</File>
<File
RelativePath=".\LipSync.cpp">
</File>
<File
RelativePath="MainMenu.cpp">
</File>
<File
RelativePath="MenuSystem.cpp">
</File>
<File
RelativePath=".\NetEntityInfo.cpp">
</File>
<File
RelativePath="RandomExprLoadSink.cpp">
</File>
<File
RelativePath="ScriptObjectAdvCamSystem.cpp">
</File>
<File
RelativePath="ScriptObjectRenderer.cpp">
</File>
<File
RelativePath=".\ScriptTimerMgr.cpp">
</File>
<File
RelativePath="Spectator.cpp">
</File>
<File
RelativePath=".\StdAfx.cpp">
<FileConfiguration
Name="Debug|Xbox">
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"/>
</FileConfiguration>
<FileConfiguration
Name="Release|Xbox">
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"/>
</FileConfiguration>
<FileConfiguration
Name="Profile|Xbox">
<Tool
Name="VCCLCompilerTool"
UsePrecompiledHeader="1"/>
</FileConfiguration>
</File>
<File
RelativePath=".\StringTableMgr.cpp">
</File>
<File
RelativePath="WeaponClass.cpp">
</File>
<File
RelativePath="WeaponSystemEx.cpp">
</File>
<File
RelativePath="XArea.cpp">
</File>
<File
RelativePath="XButton.cpp">
</File>
<File
RelativePath=".\XClientSnapshot.cpp">
</File>
<File
RelativePath="XControlPage.cpp">
</File>
<File
RelativePath=".\XDemoMgr.cpp">
</File>
<File
RelativePath="XEditBox.cpp">
</File>
<File
RelativePath=".\XEntityProcessingCmd.cpp">
</File>
<File
RelativePath="XGUIControl.cpp">
</File>
<File
RelativePath="XListBox.cpp">
</File>
<File
RelativePath=".\XNetwork.cpp">
</File>
<File
RelativePath="XObjectProxy.cpp">
</File>
<File
RelativePath=".\XPath.cpp">
</File>
<File
RelativePath=".\XPathSystem.cpp">
</File>
<File
RelativePath=".\XPlayer.cpp">
</File>
<File
RelativePath="XPlayerCamera.cpp">
</File>
<File
RelativePath="XPlayerLight.cpp">
</File>
<File
RelativePath="XPullDownMenu.cpp">
</File>
<File
RelativePath=".\XPuppetProxy.cpp">
</File>
<File
RelativePath="XStatic.cpp">
</File>
<File
RelativePath=".\XSurfaceMgr.cpp">
</File>
<File
RelativePath="XVehicleProxy.cpp">
</File>
<File
RelativePath="XVehicleProxyHeli.cpp">
</File>
<File
RelativePath="XplayerVehicle.cpp">
</File>
<Filter
Name="UI"
Filter="">
<File
RelativePath="UI.cpp">
</File>
<File
RelativePath=".\UIHud.cpp">
</File>
</Filter>
<Filter
Name="ScriptObjects"
Filter="">
<File
RelativePath=".\ScriptObjectAI.cpp">
</File>
<File
RelativePath="ScriptObjectBoids.cpp">
</File>
<File
RelativePath="ScriptObjectClient.cpp">
</File>
<File
RelativePath=".\ScriptObjectEntity.cpp">
</File>
<File
RelativePath="ScriptObjectGUI.cpp">
</File>
<File
RelativePath=".\ScriptObjectGame.cpp">
</File>
<File
RelativePath=".\ScriptObjectInput.cpp">
</File>
<File
RelativePath=".\ScriptObjectLanguage.cpp">
</File>
<File
RelativePath=".\ScriptObjectPlayer.cpp">
</File>
<File
RelativePath="ScriptObjectServer.cpp">
</File>
<File
RelativePath="ScriptObjectServerSlot.cpp">
</File>
<File
RelativePath="ScriptObjectSpectator.cpp">
</File>
<File
RelativePath=".\ScriptObjectStream.cpp">
</File>
<File
RelativePath=".\ScriptObjectVehicle.cpp">
</File>
<File
RelativePath=".\ScriptObjectWeapon.cpp">
</File>
</Filter>
<Filter
Name="GameServer"
Filter="">
<File
RelativePath=".\XServer.cpp">
</File>
<File
RelativePath=".\XServerRules.cpp">
</File>
<File
RelativePath=".\XServerSlot.cpp">
</File>
<File
RelativePath=".\XSnapshot.cpp">
</File>
</Filter>
<Filter
Name="GameSystem"
Filter="">
<File
RelativePath=".\XSystemBase.cpp">
</File>
<File
RelativePath=".\XSystemClient.cpp">
</File>
<File
RelativePath=".\XSystemDummy.cpp">
</File>
<File
RelativePath=".\XSystemServer.cpp">
</File>
</Filter>
<Filter
Name="Weapons"
Filter="">
<File
RelativePath=".\XWeapon.cpp">
</File>
<File
RelativePath=".\XWeaponSystem.cpp">
</File>
</Filter>
<Filter
Name="GameClient"
Filter="">
<File
RelativePath=".\XClient.cpp">
</File>
</Filter>
<Filter
Name="Flock"
Filter="">
<File
RelativePath="Flock.cpp">
</File>
<File
RelativePath="Flock.h">
</File>
</Filter>
<Filter
Name="Vehicle"
Filter="">
<File
RelativePath=".\XVehicle.cpp">
</File>
<File
RelativePath=".\XVehicleSystem.cpp">
</File>
</Filter>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl">
<File
RelativePath="AIHandler.h">
</File>
<File
RelativePath=".\CryGame.h">
</File>
<File
RelativePath=".\EntityClassRegistry.h">
</File>
<File
RelativePath=".\Game.h">
</File>
<File
RelativePath=".\GameObject.h">
</File>
<File
RelativePath=".\GameShared.h">
</File>
<File
RelativePath=".\IXSystem.h">
</File>
<File
RelativePath=".\IngameDialog.h">
</File>
<File
RelativePath=".\LipSync.h">
</File>
<File
RelativePath="MainMenu.h">
</File>
<File
RelativePath="MenuSystem.h">
</File>
<File
RelativePath=".\NetEntityInfo.h">
</File>
<File
RelativePath=".\PlayerSystem.h">
</File>
<File
RelativePath=".\ScriptObjectAI.h">
</File>
<File
RelativePath="ScriptObjectBoids.h">
</File>
<File
RelativePath="ScriptObjectClient.h">
</File>
<File
RelativePath=".\ScriptObjectEntity.h">
</File>
<File
RelativePath="ScriptObjectGUI.h">
</File>
<File
RelativePath=".\ScriptObjectGame.h">
</File>
<File
RelativePath=".\ScriptObjectInput.h">
</File>
<File
RelativePath=".\ScriptObjectLanguage.h">
</File>
<File
RelativePath="ScriptObjectMovie.h">
</File>
<File
RelativePath=".\ScriptObjectPlayer.h">
</File>
<File
RelativePath=".\ScriptObjectScript.h">
</File>
<File
RelativePath="ScriptObjectServer.h">
</File>
<File
RelativePath="ScriptObjectServerSlot.h">
</File>
<File
RelativePath="ScriptObjectSpectator.h">
</File>
<File
RelativePath=".\ScriptObjectStream.h">
</File>
<File
RelativePath=".\ScriptObjectVehicle.h">
</File>
<File
RelativePath=".\ScriptObjectWeapon.h">
</File>
<File
RelativePath=".\ScriptTimerMgr.h">
</File>
<File
RelativePath="Spectator.h">
</File>
<File
RelativePath=".\StdAfx.h">
</File>
<File
RelativePath=".\StringTableMgr.h">
</File>
<File
RelativePath=".\TagPoint.h">
</File>
<File
RelativePath="UI.h">
</File>
<File
RelativePath=".\UIHud.h">
</File>
<File
RelativePath="XArea.h">
</File>
<File
RelativePath="XButton.h">
</File>
<File
RelativePath=".\XClient.h">
</File>
<File
RelativePath=".\XClientSnapshot.h">
</File>
<File
RelativePath="XControlPage.h">
</File>
<File
RelativePath=".\XDemoMgr.h">
</File>
<File
RelativePath="XEditBox.h">
</File>
<File
RelativePath=".\XEntityProcessingCmd.h">
</File>
<File
RelativePath="XGUIControl.h">
</File>
<File
RelativePath="XListBox.h">
</File>
<File
RelativePath=".\XNetwork.h">
</File>
<File
RelativePath="XObjectProxy.h">
</File>
<File
RelativePath=".\XPath.h">
</File>
<File
RelativePath=".\XPathSystem.h">
</File>
<File
RelativePath=".\XPlayer.h">
</File>
<File
RelativePath="XPullDownMenu.h">
</File>
<File
RelativePath=".\XPuppetProxy.h">
</File>
<File
RelativePath=".\XServer.h">
</File>
<File
RelativePath=".\XServerRules.h">
</File>
<File
RelativePath=".\XServerSlot.h">
</File>
<File
RelativePath=".\XSnapshot.h">
</File>
<File
RelativePath="XStatic.h">
</File>
<File
RelativePath=".\XSurfaceMgr.h">
</File>
<File
RelativePath=".\XSystemBase.h">
</File>
<File
RelativePath=".\XSystemClient.h">
</File>
<File
RelativePath=".\XSystemDummy.h">
</File>
<File
RelativePath=".\XSystemServer.h">
</File>
<File
RelativePath=".\XVehicle.h">
</File>
<File
RelativePath="XVehicleProxy.h">
</File>
<File
RelativePath=".\XVehicleSystem.h">
</File>
<File
RelativePath=".\XWeapon.h">
</File>
<File
RelativePath=".\XWeaponSystem.h">
</File>
</Filter>
<Filter
Name="Resource Files"
Filter="ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe">
</Filter>
<File
RelativePath=".\ReadMe.txt">
</File>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = "file:F:\\Crytek\\CryGame\\CryGame_XBox.vcproj"
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT"
}

BIN
CryGame/DivxMediaLib32.lib Normal file

Binary file not shown.

BIN
CryGame/DivxMediaLib64.lib Normal file

Binary file not shown.

View File

@@ -0,0 +1,325 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// EntityClassRegistry.cpp: implementation of the CEntityClassRegistry class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "EntityClassRegistry.h"
#include "IScriptSystem.h"
#include <StlUtils.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CEntityClassRegistry::CEntityClassRegistry()
{
MoveFirst();
}
//////////////////////////////////////////////////////////////////////////
CEntityClassRegistry::~CEntityClassRegistry()
{
}
//////////////////////////////////////////////////////////////////////////
void CEntityClassRegistry::ResetClassRegistry()
{
if(m_pScriptSystem){
EntityClassMapItor itor=m_vEntityClasses.begin();
while(itor!=m_vEntityClasses.end())
{
m_pScriptSystem->SetGlobalToNull(itor->second.strClassName.c_str());
m_pScriptSystem->UnloadScript(itor->second.strFullScriptFile.c_str());
++itor;
}
m_vEntityClasses.clear();
}
}
// Initializes the ClassRegistry. Must be called before usage of any other functions in this class.
//////////////////////////////////////////////////////////////////////////
void CEntityClassRegistry::Init( ISystem *pSystem )
{
m_pSystem = pSystem;
m_pScriptSystem = m_pSystem->GetIScriptSystem();
ResetClassRegistry();
InitRegistry();
}
//////////////////////////////////////////////////////////////////////////
void CEntityClassRegistry::SetGameType( const string &sGameType )
{
m_sGameType=sGameType;
// Unload all entity scripts.
if(m_pScriptSystem)
{
EntityClassMapItor itor=m_vEntityClasses.begin();
while(itor!=m_vEntityClasses.end())
{
EntityClass *pEntClass = &(itor->second);
if (pEntClass->bLoaded)
{
m_pScriptSystem->SetGlobalToNull(itor->second.strClassName.c_str());
m_pScriptSystem->UnloadScript(itor->second.strFullScriptFile.c_str());
}
pEntClass->bLoaded = false;
++itor;
}
}
}
void CEntityClassRegistry::Debug()
{
EntityClassMapItor itor;
itor=m_vEntityClasses.begin();
while(itor!=m_vEntityClasses.end())
{
char str[256];
sprintf(str," CEntityClassRegistry::Debug %c %d '%s'\n",
itor->second.bLoaded?'1':'0',itor->first,itor->second.strClassName.c_str());
OutputDebugString(str);
++itor;
}
}
// Register a new class in the registry.
//////////////////////////////////////////////////////////////////////////
bool CEntityClassRegistry::AddClass(const EntityClassId _ClassId,const char* sClassName,const char* sScriptFile,bool bReserved, bool bForceReload)
{
ILog *pLog = m_pSystem->GetILog();
EntityClass ec;
//is the id already used?
if(GetByClassId(_ClassId,false)!=NULL && !bForceReload)
{
CryError( "<EntityClassRegistry> AddClass called with duplicate ClassID ID=%d Class=\"%s\"",(int)_ClassId,sClassName );
return false;
}
if (GetByClass(sClassName,false)!=NULL)
{
CryError( "<EntityClassRegistry> AddClass called with duplicate Class Name ID=%d Class=\"%s\"",(int)_ClassId,sClassName );
return false;
}
string sFilename;
//Timur[5/8/2002]
if (strlen(sScriptFile) > 0)
{
// Adds class with no script file.
// lets try to load the script from the current gametype-folder
if (m_sGameType.empty())
#if defined(LINUX)
sFilename=string("Scripts/Default/Entities/")+sScriptFile;
#else
sFilename=string("Scripts\\Default\\Entities\\")+sScriptFile;
#endif
else
#if defined(LINUX)
sFilename="Scripts/"+m_sGameType+"/Entities/"+sScriptFile;
#else
sFilename="Scripts\\"+m_sGameType+"\\Entities\\"+sScriptFile;
#endif
}
ec.ClassId=_ClassId;
ec.strClassName=sClassName;
ec.strScriptFile=sScriptFile;
ec.strFullScriptFile = sFilename;
ec.bReserved=bReserved;
m_vEntityClasses[_ClassId] = ec;
return true;
}
// Retrieve a class-description by the class-name
//////////////////////////////////////////////////////////////////////////
EntityClass *CEntityClassRegistry::GetByClass(const char *sClassName,bool bAutoLoadScript)
{
//<<FIXME>> optimize this
EntityClassMapItor itor;
itor=m_vEntityClasses.begin();
while(itor!=m_vEntityClasses.end())
{
if (stricmp(itor->second.strClassName.c_str(),sClassName) == 0)
{
if(!itor->second.bLoaded && bAutoLoadScript)
{
if (!LoadRegistryEntry(&itor->second,true))
return NULL;
}
return &(itor->second);
}
++itor;
}
return NULL;
}
// Retrieve a class-description by the class-id
//////////////////////////////////////////////////////////////////////////
EntityClass *CEntityClassRegistry::GetByClassId(const EntityClassId _ClassId,bool bAutoLoadScript)
{
//<<FIXME>> optimize this
EntityClassMapItor itor = m_vEntityClasses.find( _ClassId );
if (itor!=m_vEntityClasses.end())
{
if(!itor->second.bLoaded && bAutoLoadScript)
{
if (!LoadRegistryEntry(&itor->second,true))
return NULL;
}
return &itor->second;
}
return NULL;
}
// Move the ClassIterator to the first element.
//////////////////////////////////////////////////////////////////////////
void CEntityClassRegistry::MoveFirst()
{
m_itor=m_vEntityClasses.begin();
}
// Retrieve the next class-description.
//////////////////////////////////////////////////////////////////////////
EntityClass *CEntityClassRegistry::Next()
{
EntityClass *pEntityClass=NULL;
if(m_itor==m_vEntityClasses.end())
return NULL;
pEntityClass=&(m_itor->second);
++m_itor;
return pEntityClass;
}
// Retrieves the number of classes in the registry.
//////////////////////////////////////////////////////////////////////////
int CEntityClassRegistry::Count()
{
return m_vEntityClasses.size();
}
//////////////////////////////////////////////////////////////////////////
bool CEntityClassRegistry::LoadRegistryEntry(EntityClass * pClass,bool bForceReload )
{
assert( pClass );
ILog *pLog = m_pSystem->GetILog();
if (pClass->bLoaded && !bForceReload)
return true;
if (!m_pScriptSystem || pClass->strScriptFile.size()==0)
return true; // no script attached (entities like cameras etc...)
#if defined(LINUX)
bool bStartsWithSlash = false;
if(m_sGameType.size() > 0)
if((m_sGameType.c_str()[0] == '/') || (m_sGameType.c_str()[0] == '\\'))
bStartsWithSlash = true;
string sFilename=(bStartsWithSlash?"Scripts/":"Scripts")+m_sGameType+"/Entities/"+pClass->strScriptFile;
#else
string sFilename="Scripts\\"+m_sGameType+"\\Entities\\"+pClass->strScriptFile;
#endif
pClass->strFullScriptFile = sFilename;
if (m_sGameType.empty() || !m_pScriptSystem->ExecuteFile(sFilename.c_str(), false,bForceReload))
{
// failed, so try to load it from the default-folder
if (pLog)
{
string sMessage=sFilename +" is not available. Loading default script.";
pLog->LogToFile(sMessage.c_str());
}
#if defined(LINUX)
sFilename=string("Scripts/Default/Entities/")+pClass->strScriptFile;
#else
sFilename=string("Scripts\\Default\\Entities\\")+pClass->strScriptFile;
#endif
pClass->strFullScriptFile = sFilename;
if (!m_pScriptSystem->ExecuteFile(sFilename.c_str(),true,bForceReload))
{
// failed too: return...
string sMessage=sFilename+" Can't be loaded, script not found !";
GameWarning( sMessage.c_str() );
return false;
}
}
pClass->bLoaded=true;
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CEntityClassRegistry::InitRegistry()
{
m_pSystem->GetILog()->Log("<EntityClassRegistry> Initializing");
const char *sFilename = "Scripts/ClassRegistry.lua";
// load registry lua script.
m_pScriptSystem->ExecuteFile(sFilename);
_SmartScriptObject pTable(m_pScriptSystem,true);
_SmartScriptObject pLineObj(m_pScriptSystem,true);
if (!m_pScriptSystem->GetGlobalValue("EntityClassRegistry",*pTable))
{
CryError("Cannot find EntityClassRegistry table in scripts (wrong working folder?)");
return false;
}
int i=0;
// Scan table.
while (pTable->GetAt(++i,*pLineObj))
{
int clsid;
const char *scriptfile;
const char *tablename;
const char *entity_type;
if (pLineObj->GetAt(1,entity_type) &&
pLineObj->GetAt(2,tablename) &&
pLineObj->GetAt(3,clsid) &&
pLineObj->GetAt(4,scriptfile))
{
//EntityClassMapItor itor = m_vEntityClasses.find( cTypeID );
//if (itor!=m_vEntityClasses.end())
EntityClassId ClassId=(EntityClassId)clsid;
EntityClass *pEntityClass = GetByClassId(ClassId,false);
if (pEntityClass)
{
GameWarning( "<EntityClassRegistry> Duplicate Class ID, ClsId=%d already registered for class %s",clsid,pEntityClass->strClassName.c_str() );
}
if (!AddClass(ClassId,tablename,scriptfile,true))
{
GameWarning( "<EntityClassRegistry> AddClass failed, Class group='%s' clsid=%d name='%s' script='%s'",entity_type,clsid,tablename,scriptfile );
continue;
}
pEntityClass = GetByClassId(ClassId,false);
assert( pEntityClass ); // Cannot happen.
pEntityClass->bReserved = true;
pEntityClass->strGameType = entity_type;
// No need to log it now.
//m_pSystem->GetILog()->Log( "Registering ClassId: Type='%s' Clsid=%d Name='%s' Script='%s'\n",entity_type,clsid,tablename,scriptfile);
}
}
return true;
}

View File

@@ -0,0 +1,74 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// EntityClassRegistry.h: interface for the CEntityClassRegistry class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_ENTITYCLASSREGISTRY_H__CDAB4B12_9A92_4747_BEB3_C4B80B4ACB3D__INCLUDED_)
#define AFX_ENTITYCLASSREGISTRY_H__CDAB4B12_9A92_4747_BEB3_C4B80B4ACB3D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
struct IScriptSystem;
typedef std::map<EntityClassId,EntityClass> EntityClassMap;
typedef EntityClassMap::iterator EntityClassMapItor;
/*
*
* This class store all entity types information (classid,classname,scriptpath)
* All types of entities must be registered here, in order to be able to spawn in the game.
*
*/
class CEntityClassRegistry :
public IEntityClassRegistry
{
public:
//! constructor
CEntityClassRegistry();
//! destructor
virtual ~CEntityClassRegistry();
//!
void ResetClassRegistry();
//!
void Init( ISystem *pSystem );
//!
void SetGameType( const string &sGameType );
//!
bool InitGameClasses();
// interface IEntityClassRegistry --------------------------------------------------------------
virtual EntityClass* GetByClass(const char *str,bool bAutoLoadScript=true);
virtual EntityClass* GetByClassId(const EntityClassId ClassId,bool bAutoLoadScript=true);
virtual bool AddClass( const EntityClassId TypeID,const char* sClassName,const char* sScriptFile,bool bReserved=false,bool bForceReload=false );
virtual void MoveFirst();
virtual EntityClass *Next();
virtual int Count();
virtual bool LoadRegistryEntry(EntityClass * pClass, bool bForceReload=false);
virtual void Debug();
// --------------------------------------------------------------------------------------------
//
unsigned MemStats();
private:
//!
bool InitRegistry();
EntityClassMap m_vEntityClasses;
ISystem * m_pSystem;
IScriptSystem * m_pScriptSystem;
string m_sGameType;
EntityClassMapItor m_itor;
};
#endif // !defined(AFX_ENTITYCLASSREGISTRY_H__CDAB4B12_9A92_4747_BEB3_C4B80B4ACB3D__INCLUDED_)

21
CryGame/FireType.h Normal file
View File

@@ -0,0 +1,21 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef FIRETYPE_H
#define FIRETYPE_H
enum eFireType
{
ePressing = 0x01,
eHolding = 0x02,
eReleasing = 0x04,
eCancel= 0x08, // cancel current target
eNotFiring = 0x10,
};
#endif

1679
CryGame/Flock.cpp Normal file

File diff suppressed because it is too large Load Diff

393
CryGame/Flock.h Normal file
View File

@@ -0,0 +1,393 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001.
// -------------------------------------------------------------------------
// File name: flock.h
// Version: v1.00
// Created: 5/4/2002 by Timur.
// Compilers: Visual C++ 7.0
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __flock_h__
#define __flock_h__
#if _MSC_VER > 1000
#pragma once
#endif
#include "GameObject.h"
class CFlock;
enum EFlockType
{
EFLOCK_BIRDS,
EFLOCK_FISH,
EFLOCK_BUGS,
};
struct SBoidContext
{
Vec3 playerPos;
Vec3 flockPos;
//! Some integer for various behaviors.
int behavior;
float fSpawnRadius;
float fBoidRadius;
float fBoidMass;
float fGravity;
float terrainZ;
float waterLevel;
// Flock constants.
float MinHeight;
float MaxHeight;
// Attraction distances.
float MaxAttractDistance;
float MinAttractDistance;
// Speed.
float MaxSpeed;
float MinSpeed;
// AI factors.
// Group behavior factors.
float factorAlignment;
float factorCohesion;
float factorSeparation;
// Other behavior factors.
float factorAttractToOrigin;
float factorKeepHeight;
float factorAvoidLand;
//! Cosine of boid field of view angle.
//! Other boids which are not in field of view of this boid not considered as a neightboards.
float cosFovAngle;
//! Maximal Character animation speed.
float MaxAnimationSpeed;
// Settings.
bool followPlayer;
bool avoidObstacles;
bool noLanding;
//! Max visible distane of flock from player.
float maxVisibleDistance;
//! Size of boid.
float boidScale;
I3DEngine *engine;
IPhysicalWorld *physics;
IEntity* entity;
};
/*! This is flock creation context passed to flock Init method.
*/
struct SBoidsCreateContext
{
int boidsCount; //! Number of boids in flock.
std::vector<string> models; //! Geometry models (Static or character) to be used for flock.
string characterModel; //! Character model.
string animation; //! Looped character animation.
};
//////////////////////////////////////////////////////////////////////////
// BoidObject.
//////////////////////////////////////////////////////////////////////////
/*! Single Boid object.
*/
class CBoidObject
{
public:
CBoidObject( SBoidContext &bc );
virtual ~CBoidObject();
virtual void Update( float dt,SBoidContext &bc ) {};
virtual void Physicalize( SBoidContext &bc );
//! Kill this boid object.
//! @param force Force vector applyed on dying boid (shot vector).
virtual void Kill( const Vec3 &hitPoint,const Vec3 &force,string &surfaceName ) {};
virtual void OnFlockMove( SBoidContext &bc ) {};
virtual void Render( SRendParams &rp,CCamera &cam,SBoidContext &bc );
void CalcFlockBehavior( SBoidContext &bc,Vec3 &vAlignment,Vec3 &vCohesion,Vec3 &vSeparation );
void CalcMovement( float dt,SBoidContext &bc,bool banking );
void CalcMatrix( Matrix44 &mtx );
void CreateRigidBox( SBoidContext &bc,const Vec3 &size,float density );
void CreateArticulatedCharacter( SBoidContext &bc,const Vec3 &size,float density );
public:
//////////////////////////////////////////////////////////////////////////
friend class CFlock;
IPhysicalEntity *m_pPhysics;
CFlock *m_flock; //!< Flock of this boid.
Vec3 m_pos; //!< Boid position.
Vec3 m_heading; //!< Current heading direction.
Vec3 m_accel; //!< Current acceleration vector.
float m_speed; //!< Speed of bird at heading direction.
float m_banking; //!< Amount of banking to apply on boid.
ICryCharInstance *m_object; //< Geometry of this boid.
float m_alignHorizontally; // 0-1 to align bird horizontally when it lands.
// Flags.
unsigned m_dead : 1; //! Boid is dead, do not update it.
unsigned m_dying : 1; //! Boid is dying.
unsigned m_physicsControlled : 1; //! Boid is controlled by physics.
unsigned m_inwater : 1; //! When boid falls in water.
unsigned m_nodraw : 1; //! Do not draw this boid.
};
//////////////////////////////////////////////////////////////////////////
class CBoidBird : public CBoidObject
{
public:
CBoidBird( SBoidContext &bc );
virtual ~CBoidBird();
virtual void Update( float dt,SBoidContext &bc );
virtual void Kill( const Vec3 &hitPoint,const Vec3 &force,string &surfaceName );
virtual void OnFlockMove( SBoidContext &bc );
//void Render( CCamera &cam,SBoidContext &bc );
void Think( SBoidContext &bc );
void TakeOff( SBoidContext &bc );
private:
float m_flightTime; //!< Time flying after take off.
float m_lastThinkTime; //! Time of last think operation.
float m_maxFlightTime; // Time this bird can be in flight.
float m_desiredHeigh; // Deisred height this birds want to fly at.
Vec3 m_birdOriginPos;
// Flags.
unsigned m_onGround : 1; //! True if stand on ground.
unsigned m_landing : 1; //! True if bird wants to land.
unsigned m_takingoff : 1; //! True if bird is just take-off from land.
};
//////////////////////////////////////////////////////////////////////////
//! Boid object with fish behavior.
//////////////////////////////////////////////////////////////////////////
class CBoidFish : public CBoidObject
{
public:
CBoidFish( SBoidContext &bc );
~CBoidFish();
virtual void Update( float dt,SBoidContext &bc );
virtual void Kill( const Vec3 &hitPoint,const Vec3 &force,string &surfaceName );
private:
void SpawnBubble( const Vec3 &pos,SBoidContext &bc );
float m_dyingTime; // Deisred height this birds want to fly at.
CScriptObjectVector vec_Bubble;
HSCRIPTFUNCTION m_pOnSpawnBubbleFunc;
};
//! Structure passed to CFlock::RayTest method, filled with intersection parameters.
struct SFlockHit {
//! Hit object.
CBoidObject *object;
//! Distance from ray origin to the hit distance.
float dist;
};
//////////////////////////////////////////////////////////////////////////
class CFlockManager;
/*!
* Define flock of boids, where every boid share common properties and recognize each other.
*/
class CFlock : public CGameObject//IEntityContainer
{
public:
CFlock( int id,CFlockManager *mgr );
virtual ~CFlock();
//! Create boids in flock.
//! Must be overriden in derived specialized flocks.
virtual void CreateBoids( SBoidsCreateContext &ctx ) {};
void SetName( const char *name );
const char* GetName() const { return m_name; };
int GetId() const { return m_id; };
EFlockType GetType() const { return m_type; };
void SetPos( const Vec3& pos );
Vec3 GetPos() const { return m_origin; };
void AddBoid( CBoidObject *boid );
int GetBoidsCount() { return m_boids.size(); }
CBoidObject* GetBoid( int index ) { return m_boids[index]; }
float GetMaxVisibilityDistance() const { return m_bc.maxVisibleDistance; };
//! Retrieve general boids settings in this flock.
void GetBoidSettings( SBoidContext &bc ) { bc = m_bc; };
//! Set general boids settings in this flock.
void SetBoidSettings( SBoidContext &bc );
bool IsFollowPlayer() const { return m_bc.followPlayer; };
void ClearBoids();
//! Check ray to flock intersection.
bool RayTest( Vec3 &raySrc,Vec3 &rayTrg,SFlockHit &hit );
const char* GetModelName() const { return m_model; };
//! Static function that initialize defaults of boids info.
static void GetDefaultBoidsContext( SBoidContext &bc );
//! Enable/Disable Flock to be updated and rendered.
void SetEnabled( bool bEnabled );
//! True if this flock is enabled, and must be updated and rendered.
bool IsEnabled() const { return m_bEnabled; }
//! Set how much percent of flock is visible.
//! value 0 - 100.
void SetPercentEnabled( int percent );
//! See if this flock must be active now.
bool IsFlockActive() const;
//! flock's container should not be saved
bool IsSaveable() { return(false); }
//! Get entity owning this flock.
IEntity* GetEntity() const { return m_pEntity; }
//////////////////////////////////////////////////////////////////////////
// IEntityContainer implementation.
//////////////////////////////////////////////////////////////////////////
virtual bool Init() { return true; };
virtual void Update();
virtual void SetEntity( IEntity* entity );
virtual void OnSetAngles( const Vec3 &ang ) {};
virtual bool Write(CStream &stm,EntityCloneState *cs=NULL) { return true; };
virtual bool Read(CStream &stm) { return true; };
virtual IScriptObject *GetScriptObject() { return 0; };
virtual void SetScriptObject(IScriptObject *object) {};
virtual void Release() {};
virtual bool QueryContainerInterface( ContainerInterfaceType desired_interface, void **pInterface) { return false; };
virtual void GetEntityDesc( CEntityDesc &desc ) const {};
virtual void OnDraw(const SRendParams & EntDrawParams);
virtual void PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime);
//////////////////////////////////////////////////////////////////////////
public:
friend class CFlockManager;
//! Manager that owns flock.
CFlockManager *m_flockMgr;
protected:
typedef std::vector<CBoidObject*> Boids;
Boids m_boids;
Vec3 m_origin;
// Bonding box.
AABB m_bounds;
//! All boid parameters.
SBoidContext m_bc;
//! Uniq id of this flock, assigned by flock manager at creation.
int m_id;
//! Name of this flock.
EFlockType m_type;
char m_name[64];
char m_model[64];
// Pointer to entity who created this flock.
IEntity* m_pEntity;
bool m_bEnabled;
int m_updateFrameID;
int m_percentEnabled;
};
//////////////////////////////////////////////////////////////////////////
// Sepcialized flocks for birds and fish.
//////////////////////////////////////////////////////////////////////////
class CBirdsFlock : public CFlock
{
public:
CBirdsFlock( int id,CFlockManager *mgr ) : CFlock( id,mgr ) {};
virtual void CreateBoids( SBoidsCreateContext &ctx );
};
//////////////////////////////////////////////////////////////////////////
class CFishFlock : public CFlock
{
public:
CFishFlock( int id,CFlockManager *mgr ) : CFlock( id,mgr ) {};
virtual void CreateBoids( SBoidsCreateContext &ctx );
};
//////////////////////////////////////////////////////////////////////////
class CFlockManager
{
public:
CFlockManager( ISystem *system );
~CFlockManager();
CFlock* CreateFlock( EFlockType type );
void RemoveFlock( CFlock *flock );
CFlock* GetFlock( int id );
CFlock* FindFlock( const char *sFlockName );
//! Check ray to flock intersection.
//! @param raySrc Source point of ray.
//! @param rayTrg Target point of ray.
//! @param hit Output structure filled if ray intersected any boid.
//! @param onlyVisible If true ray hit will only consider currently visible flocks.
//! @return true if any boid object was hit, overwise false.
bool RayTest( Vec3 &raySrc,Vec3 &rayTrg,SFlockHit &hit,bool onlyVisible=true );
ISystem *GetSystem() { return m_system; };
void Update( float dt,Vec3 &playerPos );
void Render();
void ClearFlocks();
Vec3 GetPlayerPos() const { return m_playerPos; }
bool IsFlockVisible( CFlock *flock );
bool IsFlocksEnabled() const { return m_e_flocks != 0; };
public:
typedef std::vector<CFlock*> Flocks;
Flocks m_flocks;
ISystem *m_system;
IStatObj *m_object;
Vec3 m_playerPos;
int m_lastFlockId;
static int m_e_flocks;
static int m_e_flocks_hunt; // Hunting mode...
};
#endif // __flock_h__

1952
CryGame/Game.cpp Normal file

File diff suppressed because it is too large Load Diff

952
CryGame/Game.h Normal file
View File

@@ -0,0 +1,952 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code
//
// File: Game.h
//
// History:
// -August 02,2001: Create by Alberto Demichelis
// -Sep 24,2001 Modified by Petar Kotevski
//
//////////////////////////////////////////////////////////////////////
#ifndef GAME_GAME_H
#define GAME_GAME_H
#if _MSC_VER > 1000
# pragma once
#endif
//////////////////////////////////////////////////////////////////////
#ifdef FARCRYDLL_EXPORTS
#define GAMEAPI __declspec(dllexport)
#else
#define GAMEAPI __declspec(dllimport)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////
// Version of the game
#define GAME_MAIN_VERSION 1 //!< [0..255]
#define GAME_SUB_VERSION 3 //!< [0..255] patch version number, shown in menu
#define GAME_PATCH_VERSION 3 //!< [0..256*256[
#define SERVERINFO_FORMAT_VERSION 87 //!< [0..255] bump if server info format changes (old version won't show up any more)
#define NETWORK_FORMAT_VERSION 5 //!< [0..2^32] bump if netcode stream format changes
#define SAVEVERSION 23 // [Petar] Do not bump this value anymore it shows the release version of the savegame - it will always be supported
#define PATCH1_SAVEVERSION 24 // [Kirill] Do not bump this value anymore it shows the Patch 1 version of the savegame - it will always be supported
#define PATCH2_SAVEVERSION 36 //!< bump this if the savegame format changes and we are still working on patch 2
#define GAME_VERSION_SUFIX "F" //!< A - alpha, B - beta, RC - release candidate, F - final
#define MAKE_GAME_VERSION(m,s,p) (((m)<<24)|((s)<<16)|(p))
#define GAME_VERSION MAKE_GAME_VERSION(GAME_MAIN_VERSION,GAME_SUB_VERSION,GAME_PATCH_VERSION)
#define ENTITYTYPE_PLAYER 0x00000001
#define ENTITYTYPE_WAYPOINT 0x00000002
#define ENTITYTYPE_OWNTEAM 0x00000004
#define SAVEMAGIC "CRYLEVELSAVE"
// game states
enum { CGS_INPROGRESS=0, CGS_COUNTDOWN=1, CGS_PREWAR=2, CGS_INTERMISSION=3 };
#include "XNetwork.h"
#include "BitStream_Base.h" // CBitStream_Base
#include "BitStream_Compressed.h" // CBitStream_Compressed
//forward declarations
//////////////////////////////////////////////////////////////////////
class CScriptObjectGame;
class CScriptObjectInput;
class CScriptObjectBoids;
class CScriptObjectGUI;
struct ISystem;
struct I3DEngine;
class CXServer;
class CXClient;
class CUIHud;
class CXServerRules;
class CWeaponSystemEx;
class CVehicleSystem;
class CPlayerSystem;
class CFlockManager;
class CTagPoint;
struct ITagPoint;
class CScriptObjectAI;
class CIngameDialogMgr;
class CViewLayer;
class CScriptTimerMgr;
class CTeamMgr;
class CPlayer;
class CMovieUser;
class CTimeDemoRecorder;
class CUISystem;
class CXGame;
class CGameMods;
enum EventType { EVENT_MOVECMD=0,EVENT_EXPLOSION=1,EVENT_IMPULSE=2,EVENT_VEHDAMAGE=3 };
enum ActionType { ACTIONTYPE_MOVEMENT = 1, ACTIONTYPE_COMBAT, ACTIONTYPE_GAME, ACTIONTYPE_MULTIPLAYER, ACTIONTYPE_DEBUG};
struct BaseEvent
{
int nRefCount;
virtual EventType GetType() = 0;
virtual void Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream ) = 0;
virtual void Read(CStream &stm,int &iPhysicalTime, IBitStream *pBitStream ) = 0;
virtual void Execute(CXGame *pGame) = 0;
};
struct GameEvent
{
GameEvent() {}
GameEvent(const GameEvent &src)
{
iPhysTime = src.iPhysTime;
idx = src.idx;
(pEvent = src.pEvent)->nRefCount++;
}
~GameEvent()
{
if (--pEvent->nRefCount<=0)
delete pEvent;
}
GameEvent& operator=(const GameEvent &src)
{
iPhysTime = src.iPhysTime;
idx = src.idx;
(pEvent = src.pEvent)->nRefCount++;
return *this;
}
int iPhysTime;
int idx;
BaseEvent *pEvent;
};
#include "XEntityProcessingCmd.h"
struct EventPlayerCmd : BaseEvent
{
EntityId idEntity;
CXEntityProcessingCmd cmd;
virtual EventType GetType() { return EVENT_MOVECMD; }
void Write(CStream &stm, int iPhysicalTime, IBitStream *pBitStream );
void Read(CStream &stm, int &iPhysicalTime, IBitStream *pBitStream );
void Execute(CXGame *pGame);
};
struct EventExplosion : BaseEvent
{
Vec3 pos;
float damage;
float rmin,rmax,radius;
float impulsivePressure;
int nTerrainDecalId;
int32 nShooterSSID; //!< clientID - neeeded for MP score calculations, -1 if unknown
uint16 iImpactForceMul;
uint16 iImpactForceMulFinal;
uint16 iImpactForceMulFinalTorso;
EntityId idShooter;
EntityId idWeapon;
uint8 shakeFactor; //!< 0..1
uint8 deafnessRadius; //!< 0..20
uint8 deafnessTime; //!< *0.25 to get float
uint8 rminOcc; //!< 0..1
uint8 nOccRes;
uint8 nGrow;
uint8 terrainDefSize; //!< 0..20
virtual EventType GetType() { return EVENT_EXPLOSION; }
void Write(CStream &stm, int iPhysicalTime, IBitStream *pBitStream );
void Read(CStream &stm, int &iPhysicalTime, IBitStream *pBitStream );
void Execute(CXGame *pGame);
};
struct EventPhysImpulse : BaseEvent
{
int idPhysEnt;
Vec3 impulse;
Vec3 pt;
Vec3 momentum;
bool bHasPt;
bool bHasMomentum;
virtual EventType GetType() { return EVENT_IMPULSE; }
virtual void Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream );
virtual void Read(CStream &stm,int &iPhysicalTime, IBitStream *pBitStream );
void Execute(CXGame *pGame);
};
struct EventVehicleDamage : BaseEvent
{
EntityId idVehicle;
uint8 damage;
virtual EventType GetType() { return EVENT_VEHDAMAGE; }
virtual void Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream );
virtual void Read(CStream &stm,int &iPhysicalTime, IBitStream *pBitStream );
void Execute(CXGame *pGame);
};
//#define _INTERNET_SIMULATOR
//memory stats
class ICrySizer;
typedef std::vector<string> Vec2Str;
typedef Vec2Str::iterator Vec2StrIt;
typedef std::list<CPlayer*> ListOfPlayers;
#include "IInput.h" // XActionActivationMode
struct ActionInfo
{
int nId;
string sDesc;
bool bConfigurable;
XActionActivationMode ActivationMode;
Vec2Str vecSetToActionMap; // if it is configured via "BindActionMultipleMaps" it will set the key-bindings to all action-maps in this array and leaves the others untouched
int nType;
};
typedef std::map<string,ActionInfo> ActionsEnumMap;
typedef ActionsEnumMap::iterator ActionsEnumMapItor;
typedef std::multimap<string, CTagPoint *> TagPointMap;
typedef std::map<CIPAddress, SXServerInfos> ServerInfosMap;
typedef ServerInfosMap::iterator ServerInfosVecItor;
struct PreviewMapParams
{
PreviewMapParams()
{
bRound=false;
SectorsX=0;
SectorsY=0;
}
bool bRound;
int SectorsX, SectorsY;
};
//////////////////////////////////////////////////////////////////////
#include "IGame.h"
#include <IScriptSystem.h>
#include <queue>
#include <set>
#include "EntityClassRegistry.h"
#include "StringTableMgr.h"
#include "XSurfaceMgr.h"
#include "XDemoMgr.h"
#include "XArea.h"
//////////////////////////////////////////////////////////////////////
class CXGame;
class CScriptObjectStream;
//////////////////////////////////////////////////////////////////////
typedef std::queue<string> StringQueue;
typedef std::set<string> StringSet;
class CXGame :
public IXGame,
public IServerSnooperSink,
public INETServerSnooperSink,
public IPhysicsStreamer,
public IPhysicsEventClient
{
public:
CXGame();
virtual ~CXGame();
void Reset();
void SoftReset();
// interface IGame ----------------------------------------------------------
bool Init(struct ISystem *pSystem,bool bDedicatedSrv,bool bInEditor,const char *szGameMod);
bool InitClassRegistry();
bool Update();
bool Run(bool &bRelaunch);
void Release() { delete this; }
const char *IsMODLoaded();
IGameMods* GetModsInterface();
void AllowQuicksave(bool bAllow) {m_bAllowQuicksave = bAllow;};
bool IsQuicksaveAllowed(void) {return m_bAllowQuicksave;}
//! \return 0 before was initialized, otherwise point to the GameMods
CGameMods *GetModsList() { return(m_pGameMods); }
bool IsSoundPotentiallyHearable(Vec3d &SoundPos, float fClipRadius);
void SetTerrainSurface(const char *sMaterial,int nSurfaceID){m_XSurfaceMgr.SetTerrainSurface(sMaterial,nSurfaceID);}
//! load level for the editor
bool LoadLevelForEditor(const char *pszLevelDirectory,const char *pszMissionName);
bool GetLevelMissions( const char *szLevelDir,std::vector<string> &missions );
virtual void UpdateDuringLoading();
IScriptObject *GetScriptObject();
// load level for the game
void LoadLevelCS(bool reconnect, const char *szMapName, const char *szMissionName, bool listen);
IEntity *GetMyPlayer();
// tagpoint management functions
ITagPoint *CreateTagPoint( const string &name, const Vec3 &pos, const Vec3 &angles);
virtual ITagPoint *GetTagPoint(const string &name);
void RemoveTagPoint(ITagPoint *pPoint);
bool RenameTagPoint(const string &oldname, const string &newname);
//real internal load level
//return true if is loading a saved singleplayer level(this should disappear)
bool IsLoadingLevelFromFile(){ return m_bIsLoadingLevelFromFile; }
ISystem *GetSystem() { return m_pSystem; }
IScriptSystem *GetScriptSystem(){return m_pScriptSystem;}
virtual IEntityClassRegistry *GetClassRegistry() { return &m_EntityClassRegistry;}
CUIHud* GetHud() const { return (CUIHud*)m_pUIHud; }
CXServerRules* GetRules() const;
IActionMapManager *GetActionMapManager(){ return m_pIActionMapManager; }
IXSystem *GetXSystem();
bool IsOK() { return m_bOK; }
void OnSetVar(ICVar *pVar);
// Servers management
bool StartupServer(bool listen, const char *szName = NULL);
void ShutdownServer();
// Client management
bool StartupClient();
bool StartupLocalClient();
void ShutdownClient();
void MarkClientForDestruct();
bool IsSynchronizing() { return m_bSynchronizing; }
void AdvanceReceivedEntities(int iPhysicalWorldTime);
bool HasScheduledEvents();
void ScheduleEvent(int iPhysTime, BaseEvent *pEvent);
void ScheduleEvent(IEntity *pEnt, CXEntityProcessingCmd &cmd);
//! \param shooterSSID clientID 0..255 or -1 if unknown
void ScheduleEvent(int iPhysTime, const Vec3& pos,float fDamage,float rmin,float rmax,float radius,float fImpulsivePressure,
float fShakeFactor,float fDeafnessRadius,float fDeafnessTime,float fImpactForceMul,
float fImpactForceMulFinal,float fImpactForceMulFinalTorso,
float rMinOcc,int nOccRes,int nOccGrow, IEntity *pShooter, int shooterSSID, IEntity *pWeapon,
float fTerrainDefSize,int nTerrainDecalId);
void ScheduleEvent(int iPhysTime, IEntity *pVehicle,float fDamage);
void ScheduleEvent(int iPhysTime, IPhysicalEntity *pPhysEnt,pe_action_impulse *pai);
virtual void ExecuteScheduledEvents();
void WriteScheduledEvents(CStream &stm, int &iLastEventWritten, int iTimeDelta=0);
void ReadScheduledEvents(CStream &stm);
bool UseFixedStep() { return m_iFixedStep2TimeGran!=0; }
int GetiFixedStep() { return m_iFixedStep2TimeGran; }
float GetFixedStep() { return g_MP_fixed_timestep->GetFVal(); }
int QuantizeTime(float fTime)
{
return (int)(fTime*m_frTimeGran+0.5f*sgn(fTime));
}
int SnapTime(float fTime,float fOffset=0.5f)
{
return m_iFixedStep2TimeGran ?
(int)(fTime*m_frFixedStep+0.5f*sgn(fTime))*m_iFixedStep2TimeGran : (int)(fTime*m_frTimeGran+0.5f*sgn(fTime));
}
int SnapTime(int iTime,float fOffset=0.5f)
{
return m_iFixedStep2TimeGran ?
(int)(iTime*m_fTimeGran2FixedStep+0.5f*sgn(iTime))*m_iFixedStep2TimeGran : iTime;
}
//! \param shooterSSID clientID 0..255 or -1 if unknown
void CreateExplosion(const Vec3& pos,float fDamage,float rmin,float rmax,float radius,float fImpulsivePressure,
float fShakeFactor,float fDeafnessRadius,float fDeafnessTime,
float fImpactForceMul,float fImpactForceMulFinal,float fImpactForceMulFinalTorso,
float rMinOcc,int nOccRes,int nOccGrow, IEntity *pShooter, int shooterSSID, IEntity *pWeapon,
float fTerrainDefSize,int nTerrainDecalId, bool bScheduled=false);
//! IPhysicsStreamer (physics-on-demand) callback functions
int CreatePhysicalEntity(void *pForeignData,int iForeignData,int iForeignFlags);
int DestroyPhysicalEntity(IPhysicalEntity *pent);
const char *GetForeignName(void *pForeignData,int iForeignData,int iForeignFlags);
//////////////////////////////////////////////////////////////////////////
//! physical events callback functions
void OnBBoxOverlap(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData,
IPhysicalEntity *pCollider, void *pColliderForeignData,int iColliderForeignData);
void OnStateChange(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, int iOldSimClass,int iNewSimClass);
void OnCollision(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, coll_history_item *pCollision);
int OnImpulse(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, pe_action_impulse *action);
void OnPostStep(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, float fTimeInterval);
virtual IPhysicsStreamer *GetPhysicsStreamer() { return this; }
virtual IPhysicsEventClient *GetPhysicsEventClient() { return this; }
bool ConstrainToSandbox(IEntity *pEntity);
// Ingame Dialogs
CIngameDialogMgr *GetIngameDialogManager() { return m_pIngameDialogMgr; }
void BindAction(const char *sAction,const char *sKeys,const char *sActionMap=NULL, int iKeyPos = -1);
void BindActionMultipleMaps(const char *sAction,const char *sKeys, int iKeyPos = -1);
bool CheckForAction(const char *sAction);
void ClearAction(const char *sAction);
// Stuffs...
void ProcessPMessages(const char *szMsg);
// Return the version of the game
const char *GetVersion();
//! functions to know if the current terminal is a server and/or a client
//@{
bool IsServer() { return m_pServer!=NULL; }
bool IsClient();
bool IsMultiplayer(); // can be used for disabling cheats, or disabling features which cannot be synchronised over a network game
bool IsDevModeEnable();
//@}
//! save/laod game
bool SaveToStream(CStream &stm, Vec3 *pos, Vec3 *angles,string sFilename);
bool LoadFromStream(CStream &stm, bool isdemo);
bool LoadFromStream_RELEASEVERSION(CStream &str, bool isdemo, CScriptObjectStream &scriptStream);
bool LoadFromStream_PATCH_1(CStream &str, bool isdemo, CScriptObjectStream &scriptStream);
void Save(string sFileName, Vec3 *pos, Vec3 *angles,bool bFirstCheckpoint=false );
bool Load(string sFileName);
void LoadConfiguration(const string &sSystemCfg,const string &sGameCfg);
void SaveConfiguration( const char *sSystemCfg,const char *sGameCfg,const char *sProfile);
void RemoveConfiguration(string &sSystemCfg,string &sGameCfg,const char *sProfile);
void LoadLatest();
virtual CXServer* GetServer() { return m_pServer; }
CXClient* GetClient() { return m_pClient; }
void SetViewAngles(const Vec3 &angles);
CWeaponSystemEx *GetWeaponSystemEx(){ return m_pWeaponSystemEx; }
CUISystem *GetUISystem(){ return m_pUISystem; };
void ReloadWeaponScripts();
CVehicleSystem *GetVehicleSystem(){ return m_pVehicleSystem; }
CPlayerSystem *GetPlayerSystem(){ return m_pPlayerSystem; }
IClient *CreateClient(IClientSink *pSink,bool bLocal=false)
{
return m_pNetwork->CreateClient(pSink,bLocal);
}
IServer *CreateServer(IServerSlotFactory *pSink,WORD nPort, bool listen){return m_pNetwork->CreateServer(pSink,nPort,listen);}
bool GetPreviewMapPosition(float &x, float &y, float mapx, float mapy, float sizex, float sizey, float zoom, float center_x, float center_y, bool bRound);
int GetSector(int nSectorsX, int nSectorsY, float x, float y);
void DrawMapPreview(float mapx, float mapy, float sizex, float sizey, float zoom, float center_x, float center_y, float alpha, struct PreviewMapParams *pParams=NULL);
void DrawRadar(float x, float y, float w, float h, float fRange, INT_PTR *pRadarTextures, _SmartScriptObject *pEntities, char *pRadarObjective);
// Demo recording stuff ------------------------------------------------
bool StartRecording(const char *sFileName);
void StopRecording();
bool AddDemoChunk(CStream &stm);
void StartDemoPlay(const char *sFileName);
void StopDemoPlay();
void PlaybackChunk();
// Weapons -------------------------------------------------------------
INameIterator * GetAvailableWeaponNames();
INameIterator * GetAvailableProjectileNames();
bool AddWeapon(const char *pszName);
bool RemoveWeapon(const char *pszName);
void RemoveAllWeapons();
bool AddEquipPack(XDOM::IXMLDOMNode *pPack);
bool AddEquipPack(const char *pszXML);
void SetPlayerEquipPackName(const char *pszPackName);
void RestoreWeaponPacks();
// Network -------------------------------------------------------------
//!
void RefreshServerList();
//!
void OnServerFound(CIPAddress &ip, const string &szServerInfoString, int ping);
//!
void OnNETServerFound(const CIPAddress &ip, const string &szServerInfoString, int ping);
//!
void OnNETServerTimeout(const CIPAddress &ip);
//! \return might be 0
INETServerSnooper *GetNETSnooper() { return m_pNETServerSnooper; };
//! \return might be 0
IRConSystem *GetIRConSystem() { return m_pRConSystem; };
void SendMessage(const char *str){
m_qMessages.push(str);
}
bool ExecuteScript(const char *sPath,bool bForceReload=false);
void EnableUIOverlay(bool bEnable, bool bExclusiveInput);
bool IsUIOverlay();
bool IsInMenu() { return m_bMenuOverlay; }; //!< checks if we are in menu or not
void GotoMenu(bool bTriggerOnSwitch = false); //!< arranges the message queue so that the game goes to the menu
void GotoGame(bool bTriggerOnSwitch = false); //!< arranges the message queue so that the game goes out of the menu
void MenuOn(); //!< enables menu instantly (no message)
void MenuOff(); //!< disables menu instantly (no message)
void DeleteMessage(const char *szMessage); //!< deletes all occurrences of a specified message from the message queue
const char *GetLevelName() { return m_currentLevel.c_str(); }
void ResetInputMap();
string GetLevelsFolder() const;
protected:
void SetConfigToActionMap(const char *pszActionName, ...);
//bool LoadMaterials(string sFolder);
void InitInputMap();
void InitConsoleCommands();
void InitConsoleVars();
bool IsInPause(IProcess *pProcess);
//everything related to vehicle will be in another file
//Marco's NOTE: should be the same for other cvars, code and includes,
void InitVehicleCvars();
//set the common key bindings for the specified action map.
//it reduces code redundancy and makes things more clear.
void SetCommonKeyBindings(IActionMap *pActionMap);
void OnCollectUserData(INT_PTR nValue,int nCookie); //AMD Port
public:
void ClearTagPoints();
void SetCurrentUI(CUIHud *pUI);
vector2f GetSubtitleSize(const string &szMessage, float sizex, float sizey, const string &szFontName = "default", const string &szFontEffect = "default");
void WriteSubtitle(const string &szMessage, float x, float y, float sizex, float sizey, const color4f &cColor, const string &szFontName = "default", const string &szFontEffect = "default");
bool m_bIsLoadingLevelFromFile;//!<
struct IActionMapManager* m_pIActionMapManager; //!<
bool m_bDedicatedServer; //!<
bool m_bOK; //!<
bool m_bUpdateRet; //!<
bool m_bRelaunch; //!<
bool m_bMovieSystemPaused;
ISystem * m_pSystem; //!< The system interface
ILog * m_pLog; //!<
I3DEngine * m_p3DEngine; //!< The 3D engine interface
CXServer * m_pServer; //!< The server of this computer
CXClient * m_pClient; //!< The client of this computer
int m_nDEBUG_TIMING;
float m_fDEBUG_STARTTIMER;
//! The dummy client of this computer, required to get the list of servers if
//! theres not a real client actually connected and playing
IServerSnooper * m_pServerSnooper; //!< used for LAN Multiplayer, to remove control servers
INETServerSnooper * m_pNETServerSnooper; //!< used for Internet Multiplayer, to remove control servers
IRConSystem * m_pRConSystem; //!< used for Multiplayer, to remote control servers
string m_szLastAddress;
bool m_bLastDoLateSwitch;
bool m_bLastCDAuthentication;
CUIHud * m_pUIHud; //!< Hud
CUIHud * m_pCurrentUI; //!< for the current ui
string m_currentLevel; //!< Name of current level.
string m_currentMission; //!< Name of current mission.
string m_currentLevelFolder; //!< Folder of the current level.
// console variables -----------------------------------------------------------
#ifdef _INTERNET_SIMULATOR
ICVar* g_internet_simulator_minping;
ICVar* g_internet_simulator_maxping;
ICVar* g_internet_simulator_packetloss;
#endif
ICVar* g_MP_fixed_timestep;
ICVar* g_maxfps;
ICVar* cl_ThirdPersonRange;
ICVar* cl_ThirdPersonRangeBoat;
ICVar* cl_ThirdPersonAngle;
ICVar* cl_ThirdPersonOffs;
ICVar* cl_ThirdPersonOffsAngHor;
ICVar* cl_ThirdPersonOffsAngVert;
ICVar* cl_scope_flare;
ICVar* cl_lazy_weapon;
ICVar* cl_weapon_fx;
ICVar* cl_projectile_light;
ICVar* cl_weapon_light;
ICVar* w_underwaterbubbles;
ICVar* cl_ViewFace;
ICVar* cl_display_hud;
ICVar* cl_motiontracker;
ICVar* cl_msg_notification;
ICVar* cl_hud_name;
ICVar* cl_hud_pickup_icons;
ICVar* ai_num_of_bots;
ICVar* p_name;
ICVar* p_color;
ICVar* p_model;
ICVar* mp_model;
ICVar* p_always_run;
ICVar* g_language;
ICVar* g_playerprofile;
ICVar* g_serverprofile;
ICVar* g_Render;
ICVar* g_GC_Frequence;
ICVar* g_GameType;
ICVar* g_LeftHanded;
ICVar* g_Gore;
ICVar* g_InstallerVersion;
ICVar* p_speed_run;
ICVar* p_sprint_scale;
ICVar* p_sprint_decoy;
ICVar* p_sprint_restore_run; // restore rate when normal run
ICVar* p_sprint_restore_idle; // restore rate whwen not running
ICVar* p_speed_walk;
ICVar* p_speed_crouch;
ICVar* p_speed_prone;
ICVar* p_jump_force;
ICVar* p_jump_walk_time;
ICVar* p_jump_run_time;
ICVar* p_jump_walk_d;
ICVar* p_jump_walk_h;
ICVar* p_jump_run_d;
ICVar* p_jump_run_h;
ICVar* p_gravity_modifier;
//[KIRILL] this console variable makes lean global - it has to be player's per-instance property
// to fix bug in MP with leaning
// ICVar* p_lean; // lean angle
ICVar* p_lean_offset;
ICVar* p_bob_pitch;
ICVar* p_bob_roll;
ICVar* p_bob_length;
ICVar* p_bob_weapon;
ICVar* p_bob_fcoeff;
ICVar* p_waterbob_pitch;
ICVar* p_waterbob_pitchspeed;
ICVar* p_waterbob_roll;
ICVar* p_waterbob_rollspeed;
ICVar* p_waterbob_mindepth;
ICVar* p_weapon_switch;
ICVar* p_deathtime;
ICVar* p_restorehalfhealth;
ICVar* p_ai_runspeedmult; //combat stance
ICVar* p_ai_crouchspeedmult;
ICVar* p_ai_pronespeedmult;
ICVar* p_ai_rrunspeedmult; //relaxed stance
ICVar* p_ai_rwalkspeedmult;
ICVar* p_ai_xrunspeedmult; //stealth stance
ICVar* p_ai_xwalkspeedmult;
ICVar* p_lightrange;
ICVar* p_lightfrustum;
// player animation control parametrs
ICVar* pa_leg_velmoving;
ICVar* pa_leg_velidle;
ICVar* pa_leg_idletime;
ICVar* pa_leg_limitaim;
ICVar* pa_leg_limitidle;
ICVar* pa_blend0;
ICVar* pa_blend1;
ICVar* pa_blend2;
ICVar* pa_forcerelax;
ICVar* pa_spine;
ICVar* pa_spine1;
ICVar* m_pCVarCheatMode;
// limping state
ICVar* p_limp;
// flashlight stuff
ICVar* pl_force;
ICVar* pl_dist;
ICVar* pl_intensity;
ICVar* pl_fadescale;
ICVar* pl_head;
//mutants jump parameters
ICVar* m_jump_vel;
ICVar* m_jump_arc;
// boat
//*
ICVar* b_dump; //angular velocity - waiving
ICVar* b_dumpRot; //angular velocity - turning
ICVar* b_dumpV; //velocity
ICVar* b_dumpVH; //velocity
ICVar* b_stand;
ICVar* b_turn;
ICVar* b_tilt;
ICVar* b_speedV;
ICVar* b_accelerationV;
ICVar* b_float;
ICVar* b_speedMinTurn;
// water waves param
ICVar* b_wscale;
ICVar* b_wscalew;
ICVar* b_wmomentum;
// camera mode
ICVar* b_camera;
/*
//fire/burnable
ICVar* f_update;
ICVar* f_draw;
ICVar* f_drawDbg;
*/
ICVar* g_LevelName;
ICVar* g_StartLevel;
ICVar* g_StartMission;
ICVar *sv_port;
ICVar *sv_mapcyclefile;
ICVar *sv_cheater_kick;
ICVar *sv_cheater_ban;
ICVar *sv_timeout;
ICVar *cl_timeout;
ICVar *cl_loadtimeout;
ICVar *cl_snooptimeout;
ICVar *cl_snoopretries;
ICVar *cl_snoopcount;
ICVar* p_CameraSmoothVLimit;
ICVar* p_CameraSmoothTime;
ICVar* p_CameraSmoothScale;
ICVar* p_LeaveVehicleImpuls;
ICVar* p_LeaveVehicleBrake;
ICVar* p_LeaveVehicleBrakeDelay;
ICVar* p_AutoCenterDelay;
ICVar* p_AutoCenterSpeed;
ICVar* p_HitImpulse;
ICVar* p_DeadBody;
ICVar* p_RotateHead;
ICVar* p_RotateMove;
ICVar* p_HeadCamera;
ICVar* p_EyeFire;
ICVar* a_DrawArea;
ICVar* a_LogArea;
ICVar* cv_game_Difficulty;
ICVar* cv_game_Aggression;
ICVar* cv_game_Accuracy;
ICVar* cv_game_Health;
ICVar* cv_game_AllowAIMovement;
ICVar* cv_game_AllAIInvulnerable;
ICVar* cv_game_GliderGravity;
ICVar* cv_game_GliderBackImpulse;
ICVar* cv_game_GliderDamping;
ICVar* cv_game_GliderStartGravity;
ICVar* cv_game_physics_quality;
ICVar* cv_game_subtitles;
ICVar* g_timedemo_file;
ICVar* h_drawbelow; // show bboxes for static objects below helicopter
ICVar* pl_JumpNegativeImpulse; //!< this represent the downward impulse power applied when the player reach the max height of the jump, 0 means no impulse.
ICVar* e_deformable_terrain; //!< the Cvar is created in cry3dengine, this is just a pointer
float w_recoil_speed_up;
float w_recoil_speed_down;
float w_recoil_max_degree;
float w_accuracy_decay_speed;
float w_accuracy_gain_scale;
int w_recoil_vertical_only;
CStringTableMgr m_StringTableMgr;
CXSurfaceMgr m_XSurfaceMgr;
CScriptTimerMgr *m_pScriptTimerMgr;
// IXArea *CreateArea( const Vec3 *vPoints, const int count, const char** names, const int ncount, const int type=0, const float width=0.0f);
IXArea *CreateArea( const Vec3 *vPoints, const int count, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f, const float height=0.0f );
IXArea *CreateArea( const Vec3& min, const Vec3& max, const Matrix44& TM, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f);
IXArea *CreateArea( const Vec3& center, const float radius, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f);
void DeleteArea( const IXArea *pArea );
IXArea *GetArea( const Vec3 &point );
//! detect areas the listener is in before system update
void CheckSoundVisAreas();
//! retrigger them if necessary after system update
void RetriggerAreas();
ILipSync* CreateLipSync();
//! plays a cutscene sequence
void PlaySequence(const char *pszName,bool bResetFX);
//! stops the current cutscene
void StopCurrentCutscene();
ActionsEnumMap& GetActionsEnumMap() { return m_mapActionsEnum; }
CXAreaMgr m_XAreaMgr;
ServerInfosMap m_ServersInfos; //!< Infos about the avaible servers
string m_strLastSaveGame;
bool m_bEditor;
tPlayerPersistentData m_tPlayerPersistentData;
//! Rendering callback, called at render of frame.
static void OnRenderCallback( void *pGame );
private: // ------------------------------------------------------------
bool ParseLevelName(const char *szLevelName,char *szLevel,char *szMission);
float m_fFadingStartTime;
char m_szLoadMsg[512];
bool m_bAllowQuicksave;
CEntityClassRegistry m_EntityClassRegistry;
IScriptSystem * m_pScriptSystem;
IRenderer * m_pRenderer;
IEntitySystem * m_pEntitySystem;
CScriptObjectGame * m_pScriptObjectGame;
CScriptObjectInput * m_pScriptObjectInput;
CScriptObjectBoids * m_pScriptObjectBoids;
CScriptObjectLanguage * m_pScriptObjectLanguage;
CScriptObjectAI * m_pScriptObjectAI;
CWeaponSystemEx * m_pWeaponSystemEx;
CVehicleSystem * m_pVehicleSystem;
CPlayerSystem * m_pPlayerSystem;
CIngameDialogMgr * m_pIngameDialogMgr;
CFlockManager * m_pFlockManager;
CMovieUser * m_pMovieUser;
CTimeDemoRecorder * m_pTimeDemoRecorder;
int m_nPlayerIconTexId;
int m_nVehicleIconTexId;
int m_nBuildingIconTexId;
int m_nUnknownIconTexId;
ActionsEnumMap m_mapActionsEnum; //!< Input Stuff(is for the client only but must be here)
TagPointMap m_mapTagPoints; //!< Map of tag points by name
INetwork * m_pNetwork;
CXDemoMgr m_XDemoMgr;
StringQueue m_qMessages;
bool m_bMenuInitialized;
std::vector<GameEvent> m_lstEvents;
float m_fTimeGran;
float m_fFixedStep;
float m_fTimeGran2FixedStep;
float m_frFixedStep;
float m_frTimeGran;
int m_iFixedStep2TimeGran;
int m_iLastCmdIdx;
bool m_bSynchronizing;
CBitStream_Base m_BitStreamBase; //!< for little compressed readwrite operation with CStreams (savegame,singleplayer,exported games,demo recording)
CBitStream_Compressed m_BitStreamCompressed; //!< for compressed readwrite operation with CStreams (multiplayer)
//! Name of the last saved checkpoint.
string m_sLastSavedCheckpointFilename;
/*
//! Time in seconds left to save thumbnail for the last saved checkpoint.
//! Only used when saving first checkpoint, when at time of checkpoint save nothing is yet visibly on screen.
float m_fTimeToSaveThumbnail;
*/
CGameMods * m_pGameMods; //!< might be 0 (before game init)
public:
void LoadingError(const char *szError);
bool GetCDPath(string &szCDPath);
//////////////////////////////////////////////////////////////////////////
// DevMode.
//////////////////////////////////////////////////////////////////////////
void DevModeInit();
void DevModeUpdate();
void DevMode_SavePlayerPos( int index,const char *sTagName=NULL,const char *sDescription=NULL );
void DevMode_LoadPlayerPos( int index,const char *sTagName=NULL );
//////////////////////////////////////////////////////////////////////////
// interface IGame ---------------------------------------------------------
virtual void GetMemoryStatistics(ICrySizer *pSizer);
virtual void SetViewMode(bool bThirdPerson);
//Timur[10/2/2002]void SetScriptGlobalVariables(void);
virtual void AddRespawnPoint(ITagPoint *pPoint);
virtual void RemoveRespawnPoint(ITagPoint *pPoint);
virtual void ResetState(void);
virtual void HideLocalPlayer( bool hide,bool bEditor );
virtual void ReloadScripts();
virtual bool GoreOn() const;
virtual IBitStream *GetIBitStream();
//! sets a timer for a generic script object table
int AddTimer(IScriptObject *pTable,unsigned int nStartTimer,unsigned int nTimer,IScriptObject *pUserData,bool bUpdateDuringPause);
void PlaySubtitle(ISound * pSound);
bool OpenPacks(const char *szFolder);
bool ClosePacks(const char *szFolder);
ListOfPlayers m_PlayersWithLighs; //!<
bool m_bHideLocalPlayer; //!<
CUISystem * m_pUISystem;
bool m_bMenuOverlay; //!<
bool m_bUIOverlay; //!<
bool m_bUIExclusiveInput; //!<
bool m_bMapLoadedFromCheckpoint; //!<
ListOfPlayers m_DeadPlayers;
virtual IXAreaMgr* GetAreaManager() { return &m_XAreaMgr; };
virtual ITagPointManager* GetTagPointManager();
ITagPointManager *m_pTagPointManager;
string m_sGameName;
virtual int GetInterfaceVersion() { return 1; };
virtual string& GetName() { return m_sGameName; };
virtual bool GetModuleState( EGameCapability eCap )
{
switch ( eCap )
{
case EGameMultiplayer:
return IsMultiplayer();
case EGameClient:
return IsClient();
case EGameServer:
return IsServer();
case EGameDevMode:
return IsDevModeEnable();
default:
return false;
}
};
};
#endif // GAME_GAME_H

1363
CryGame/GameActionInput.cpp Normal file

File diff suppressed because it is too large Load Diff

147
CryGame/GameCallbacks.cpp Normal file
View File

@@ -0,0 +1,147 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameCallBacks.cpp
//
// History:
// -October 31,2003: created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include "XVehicleSystem.h"
#include "XVehicle.h"
///////////////////////////////////////////////////////////////////////////
/////////////////////////// physics callbacks /////////////////////////////
//////////////////////////////////////////////////////////////////////////
int CXGame::CreatePhysicalEntity(void *pForeignData,int iForeignData,int iForeignFlags)
{
switch (iForeignData&0x0F)
{
case 0: return ((IEntity*)pForeignData)->CreatePhysicalEntityCallback(iForeignFlags); // CEntity
case 1: ((IEntityRender*)pForeignData)->Physicalize(true); return 1; // CBrush
case 2: return m_pSystem->GetI3DEngine()->PhysicalizeStaticObject(pForeignData,iForeignData,iForeignFlags); // CStatObjInst
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
int CXGame::DestroyPhysicalEntity(IPhysicalEntity *pent)
{
pe_params_foreign_data pfd;
pent->GetParams(&pfd);
switch (pfd.iForeignData&0x0F)
{
case 0: return ((IEntityRender*)pfd.pForeignData)->DestroyPhysicalEntityCallback(pent); // CEntity
case 1: ((IEntityRender*)pfd.pForeignData)->DestroyPhysicalEntityCallback(pent); return 1; // CBrush
case 2: return 2; // CStatObjInst
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
const char *CXGame::GetForeignName(void *pForeignData,int iForeignData,int iForeignFlags)
{
if (pForeignData)
switch (iForeignData)
{
case 0: return ((IEntity*)pForeignData)->GetName();
case 1: return "Brush/StatObj";
}
return "Orphan Entity";
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnBBoxOverlap(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData,
IPhysicalEntity *pCollider, void *pColliderForeignData,int iColliderForeignData)
{
if (iForeignData==0 && iColliderForeignData==0)
{
IEntity *pEntity = (IEntity*)pForeignData;
IEntity *pColliderEntity = (IEntity*)pColliderForeignData;
pEntity->OnPhysicsBBoxOverlap( pColliderEntity );
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnCollision(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, coll_history_item *pCollision)
{
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnStateChange(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, int iOldSimClass,int iNewSimClass)
{
// If foregin data is entity.
if (iForeignData==0)
{
IEntity *pEntity = ((IEntity*)pForeignData);
pEntity->OnPhysicsStateChange( iNewSimClass,iOldSimClass );
}
}
//////////////////////////////////////////////////////////////////////////
int CXGame::OnImpulse(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, pe_action_impulse *action)
{
if (iForeignData==0 && IsMultiplayer() && UseFixedStep() && ((IEntity*)pForeignData)->GetNetPresence())
{
if (IsServer())
ScheduleEvent(-1,pEntity,action);
return 0;
}
return 1;
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnPostStep(IPhysicalEntity *pEntity, void *pForeignData,int iForeignData, float fTimeInterval)
{
IEntityContainer *pCnt;
CVehicle *pVehicle;
CPlayer *pPlayer;
if (iForeignData==0 && pForeignData)
{
if (((IEntity*)pForeignData)->GetUpdateVisLevel()==eUT_PhysicsPostStep)
{
SEntityUpdateContext ctx;
ctx.nFrameID = m_pSystem->GetIRenderer() ? m_pSystem->GetIRenderer()->GetFrameID() : 0;
ctx.pCamera = &m_pSystem->GetViewCamera();
ctx.fCurrTime = m_pSystem->GetITimer()->GetCurrTime();
ctx.fFrameTime = fTimeInterval;
ctx.bProfileToLog = false;
ctx.numVisibleEntities = 0;
ctx.numUpdatedEntities = 0;
((IEntity*)pForeignData)->Update(ctx);
}
else if (pCnt=((IEntity*)pForeignData)->GetContainer())
{
if (pCnt->QueryContainerInterface(CIT_IVEHICLE, (void**)&pVehicle))
pVehicle->UpdatePhysics(fTimeInterval);
else if (pCnt->QueryContainerInterface(CIT_IPLAYER, (void**)&pPlayer))
pPlayer->UpdatePhysics(fTimeInterval);
}
}
}

View File

@@ -0,0 +1,209 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameMisc.cpp
//
// History:
// -October 31,2003: created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
//! create the server
//////////////////////////////////////////////////////////////////////////
bool CXGame::StartupServer(bool listen, const char *szName)
{
m_pLog->Log("Creating the server");
ShutdownServer(); // to be sure
int nPort = sv_port->GetIVal();
// set port and create server
if(!m_pServer)
m_pServer = new CXServer(this, nPort, szName, listen);
if (!m_pServer || !m_pServer->IsOK()) // Check if the server has been created
{
// failed, lets try a different port
m_pLog->Log("Server creation failed ! Try with another port");
SAFE_DELETE(m_pServer);
m_pServer = new CXServer(this, nPort+1, szName, listen);
sv_port->Set(nPort+1);
if (!m_pServer || !m_pServer->IsOK()) // Check if the server has been created
{
SAFE_DELETE(m_pServer);
m_pLog->Log("Server creation failed !");
return false;
}
}
if (m_pRConSystem)
m_pRConSystem->OnServerCreated(m_pServer->m_pIServer);
m_pLog->Log("Server created");
// m_pServer->Update(); // server is created but map wasn't set yet we don't want to allow connects before
return true;
}
//////////////////////////////////////////////////////////////////////
//! shutdown the server
void CXGame::ShutdownServer()
{
if(!m_pServer)
return;
if(!m_pServer->IsInDestruction())
{
m_pLog->Log("Shutdown CXServer");
SAFE_DELETE(m_pServer);
m_pLog->Log("CXServer shutdowned");
}
}
//////////////////////////////////////////////////////////////////////
//! create the client for a multiplayer session
bool CXGame::StartupClient()
{
m_pLog->Log("Creating the Client");
ShutdownClient(); // to be sure
m_pClient = new CXClient;
if (!m_pClient->Init(this)) // Check if the client has been created
{
ShutdownClient();
m_pLog->Log("Client creation failed !");
return false;
}
m_pLog->Log("Client created");
return true;
}
//! create the client for a singleplayer session
//! the client will use a fake connection
//////////////////////////////////////////////////////////////////////////
bool CXGame::StartupLocalClient()
{
m_pLog->Log("Creating the LocalClient");
m_pClient = new CXClient;
if (!m_pClient->Init(this,true)) // Check if the client has been created
{
ShutdownClient();
m_pLog->Log("LocalClient creation failed !");
return false;
}
m_pLog->Log("LocalClient created");
return true;
}
//////////////////////////////////////////////////////////////////////
//! shutdown the client
void CXGame::ShutdownClient()
{
if (!m_pClient)
return;
m_pLog->Log("Disconnect the client");
m_pClient->XDisconnect("@ClientHasQuit");
m_pLog->Log("Shutdown the Client");
m_pClient->MarkForDestruct();
m_pClient->DestructIfMarked();
m_pClient=NULL;
}
bool CXGame::IsClient()
{
return m_pClient!=NULL && !m_pClient->m_bSelfDestruct;
}
//////////////////////////////////////////////////////////////////////
//! mark the client for deletion
void CXGame::MarkClientForDestruct()
{
if(m_pClient)
m_pClient->MarkForDestruct();
}
/*! implementation of IServerSnooperSink::OnServerFound
called when a server is found after a CXGame::RefreshServerList() call
@param ip address of the server
@param stmServerInfo stream sent by the server to identitfy himself
@param ping average lantency of the server response
*/
//////////////////////////////////////////////////////////////////////////
void CXGame::OnServerFound(CIPAddress &ip, const string &szServerInfoString, int ping)
{
SXServerInfos ServerInfos;
if(ServerInfos.Read(szServerInfoString))
{
ServerInfos.IP = CIPAddress(ServerInfos.nPort,ip.GetAsString()); // get the game port from the packet
ServerInfos.nPing = ping;
m_ServersInfos[ServerInfos.IP] = ServerInfos;
TRACE("CXGame::OnServerFound %s[%s]==>%s",ServerInfos.strName.c_str(),ServerInfos.IP.GetAsString(true),ServerInfos.strMap.c_str());
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnNETServerFound(const CIPAddress &ip, const string &szServerInfoString, int ping)
{
SXServerInfos ServerInfos;
bool bOk=ServerInfos.Read(szServerInfoString);
if(bOk || IsDevModeEnable()) // in DevMode we still wanna see these servers
{
ServerInfos.IP = ip;
ServerInfos.nPing = ping;
m_pScriptObjectGame->OnNETServerFound((CIPAddress&)ip, ServerInfos);
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnNETServerTimeout(const CIPAddress &ip)
{
m_pScriptObjectGame->OnNETServerTimeout((CIPAddress&)ip);
}
/*! search the LAN for FarCry servers
remove all "old" servers from the server list before start searching
*/
//////////////////////////////////////////////////////////////////////////
void CXGame::RefreshServerList()
{
m_ServersInfos.clear();
if(m_pServerSnooper)
m_pServerSnooper->SearchForLANServers(GetCurrentTime());
TRACE("Refresh for lan");
}

300
CryGame/GameDevMode.cpp Normal file
View File

@@ -0,0 +1,300 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameMisc.cpp
//
// History:
// -October 31,2003: created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include "TimeDemoRecorder.h"
//////////////////////////////////////////////////////////////////////////
void CXGame::DevModeInit()
{
#ifdef WIN32
for (int i = 0; i < 255; i++)
{
// Reset Async state of all keys.
GetAsyncKeyState(i);
}
#endif WIN32
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::IsDevModeEnable()
{
// if there already a server we stick to the setting during creation
if(IsMultiplayer())
{
if(m_pSystem->GetForceNonDevMode())
return false;
}
// otherwise with get the info from the console variable
if (!m_pCVarCheatMode || (strcmp(m_pCVarCheatMode->GetString(),"DEVMODE")!=0))
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
void CXGame::DevModeUpdate()
{
#ifdef WIN32
m_pTimeDemoRecorder->Update();
if(m_pSystem->GetIRenderer()->GetHWND() != ::GetActiveWindow())
return;
// Check if special developmnt keys where pressed.
bool bCtrl = (GetAsyncKeyState(VK_CONTROL) & (1<<15)) != 0;
bool bShift = (GetAsyncKeyState(VK_SHIFT) & (1<<15)) != 0;
int key = 0;
for (int i = 0; i < 8; i++)
{
if (GetAsyncKeyState(VK_F1+i)&1)
{
key = i+1;
break;
}
}
// try also old F9/F10 keys
if (key == 0)
{
if(GetAsyncKeyState(VK_F9) & 1)
{
key = 1;
bCtrl = true;
}
else if(GetAsyncKeyState(VK_F10) & 1)
{
key = 1;
bShift = true;
}
}
if (key != 0)
{
if (bCtrl)
{
// Save current player position.
DevMode_SavePlayerPos(key-1);
} else if (bShift)
{
// Load current player position.
DevMode_LoadPlayerPos(key-1);
}
}
bool bCancel = GetAsyncKeyState(VK_CANCEL) & 1;
bool bTimeDemoKey = GetAsyncKeyState(VK_SNAPSHOT) & 1;
if (bCancel)
{
if (m_pTimeDemoRecorder->IsRecording())
{
// Stop and save
StopRecording();
}
// Toggle start/stop of demo recording.
if (m_pTimeDemoRecorder->IsPlaying())
{
// Stop playing.
StopDemoPlay();
}
}
//////////////////////////////////////////////////////////////////////////
// Time demo on/off
//////////////////////////////////////////////////////////////////////////
if (bCtrl && bTimeDemoKey)
{
if (!m_pTimeDemoRecorder->IsRecording())
{
// Start record.
StartRecording( g_timedemo_file->GetString() );
}
}
if (bShift && bTimeDemoKey)
{
if (!m_pTimeDemoRecorder->IsPlaying())
{
// Load and start playing.
StartDemoPlay( g_timedemo_file->GetString() );
}
}
#endif
}
//////////////////////////////////////////////////////////////////////////
void CXGame::DevMode_SavePlayerPos( int index,const char *sTagName,const char *sDescription )
{
#ifdef WIN32
if (index < 0 && index > 11)
return;
if (!IsDevModeEnable())
return;
Vec3 tagLocations[12];
Vec3 tagAngles[12];
memset( tagAngles,0,sizeof(tagAngles) );
memset( tagLocations,0,sizeof(tagLocations) );
String filename = m_currentLevelFolder + "/tags.txt";
if (sTagName)
filename = m_currentLevelFolder + "/" + sTagName + ".tagpoint";
const char *desc = "";
if (sDescription)
desc = sDescription;
// Load tag locations from file.
FILE *f = fopen( filename.c_str(),"rt" ); // Dont change this to CryPak
if (f)
{
for (int i = 0; i < 12; i++)
{
float x=0,y=0,z=0,ax=0,ay=0,az=0;
fscanf( f,"%f,%f,%f,%f,%f,%f\n",&x,&y,&z,&ax,&ay,&az );
tagLocations[i] = Vec3(x,y,z);
tagAngles[i] = Vec3(ax,ay,az);
}
fclose(f);
}
tagLocations[index] = m_pSystem->GetViewCamera().GetPos();
tagAngles[index] = m_pSystem->GetViewCamera().GetAngles();
SetFileAttributes(filename.c_str(), 0);
f = fopen( filename.c_str(),"wt" ); // Dont change this to CryPak
if (f)
{
for (int i = 0; i < 12; i++)
{
fprintf( f,"%f,%f,%f,%f,%f,%f\n",
tagLocations[i].x,tagLocations[i].y,tagLocations[i].z,
tagAngles[i].x,tagAngles[i].y,tagAngles[i].z);
}
fprintf( f,"%s\n",desc );
fclose(f);
}
else
{
GameWarning( "Cannot overwrite Tag point file %s not found (Check if read-only)",filename.c_str() );
}
if (sTagName && strlen(sTagName) > 0)
{
//////////////////////////////////////////////////////////////////////////
// Also save to Editor supported comment object .grp.
//////////////////////////////////////////////////////////////////////////
XmlNodeRef root = m_pSystem->CreateXmlNode( "Objects" );
XmlNodeRef node = root->newChild( "Object" );
node->setAttr( "Pos",tagLocations[index] );
node->setAttr( "Angles",tagAngles[index] );
node->setAttr( "Type","Comment" );
if (sDescription)
{
node->setAttr( "Name",sDescription );
node->setAttr( "Comment",sDescription );
}
else
node->setAttr( "Name",sTagName );
//node->setAttr( "ColorRGB",RGB(255,0,0) );
filename = m_currentLevelFolder + "/" + sTagName + ".grp";
root->saveToFile( filename.c_str() );
}
#endif
}
//////////////////////////////////////////////////////////////////////////
void CXGame::DevMode_LoadPlayerPos( int index,const char *sTagName )
{
#ifdef WIN32
if (index < 0 && index > 11)
return;
IEntity *pPlayer = GetMyPlayer();
if (!pPlayer)
return;
if (!IsDevModeEnable())
return;
Vec3 tagLocations[12];
Vec3 tagAngles[12];
memset( tagAngles,0,sizeof(tagAngles) );
memset( tagLocations,0,sizeof(tagLocations) );
char desc[1024];
String filename = m_currentLevelFolder + "/tags.txt";
if (sTagName)
filename = m_currentLevelFolder + "/" + sTagName + ".tagpoint";
// Load tag locations from file.
FILE *f = fopen( filename.c_str(),"rt" ); // Dont change this to CryPak
if (f)
{
for (int i = 0; i < 12; i++)
{
strcpy( desc,"" );
float x=0,y=0,z=0,ax=0,ay=0,az=0;
fscanf( f,"%f,%f,%f,%f,%f,%f,%s\n",&x,&y,&z,&ax,&ay,&az,desc );
tagLocations[i] = Vec3(x,y,z);
tagAngles[i] = Vec3(ax,ay,az);
}
fscanf( f,"%s\n",desc );
if (strlen(desc) > 0)
GameWarning( "%s",desc );
fclose(f);
}
else
{
GameWarning( "Tag file %s not found",filename.c_str() );
}
Vec3 p = tagLocations[index];
Vec3 a = tagAngles[index];
if (!p.IsZero())
{
m_pSystem->GetViewCamera().SetPos(p);
pe_player_dimensions dim;
if (pPlayer->GetPhysics())
{
dim.heightEye = 0;
pPlayer->GetPhysics()->GetParams( &dim );
p.z = p.z - dim.heightEye;
}
pPlayer->SetPos( p );
}
if (!a.IsZero())
{
m_pSystem->GetViewCamera().SetAngle(a);
SetViewAngles( a );
}
#endif
}

319
CryGame/GameEquipPacks.cpp Normal file
View File

@@ -0,0 +1,319 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameEquicpPacks.cpp
//
// History:
// -October 31,2003: created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include "WeaponSystemEx.h"
#include "WeaponClass.h"
//////////////////////////////////////////////////////////////////////////
INameIterator * CXGame::GetAvailableWeaponNames()
{
return m_pWeaponSystemEx->GetAvailableWeapons();
}
//////////////////////////////////////////////////////////////////////////
INameIterator * CXGame::GetAvailableProjectileNames()
{
return m_pWeaponSystemEx->GetAvailableProjectiles();
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::AddWeapon(const char *pszName)
{
return m_pWeaponSystemEx->AddWeapon(pszName);
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::RemoveWeapon(const char *pszName)
{
/// return m_pWeaponSystem->RemoveWeapon(pszName, this, m_pServer->m_pISystem);
return true;
}
//////////////////////////////////////////////////////////////////////////
void CXGame::RemoveAllWeapons()
{
//m_pWeaponSystem->RemoveAllWeapons(this, m_pServer->m_pISystem);
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::AddEquipPack(const char *pszXML)
{
XDOM::IXMLDOMDocumentPtr pDoc = m_pSystem->CreateXMLDocument();
if (!pDoc->loadXML(pszXML))
return false;
XDOM::IXMLDOMNodeListPtr pNodes = pDoc->getChildNodes();
if (pNodes)
{
XDOM::IXMLDOMNodePtr pEquipNode;
pNodes->reset();
while (pEquipNode = pNodes->nextNode())
AddEquipPack(pEquipNode);
}
else
return false;
return true;
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::AddEquipPack(XDOM::IXMLDOMNode *pPack)
{
_SmartScriptObject cEquipPacks(GetScriptSystem(), true);
XDOM::IXMLDOMNodePtr pPackName, pPrimaryWeapon;
GetScriptSystem()->GetGlobalValue("EquipPacks", cEquipPacks);
pPackName = pPack->getAttribute("name");
pPrimaryWeapon = pPack->getAttribute("primary");
if (pPackName)
{
// TRACE("Equipment Pack Available: %s", pPackName->getText());
_SmartScriptObject cWeaponList(GetScriptSystem(), false);
XDOM::IXMLDOMNodeListPtr pItemList = pPack->getElementsByTagName("Items");
if (pItemList)
{
XDOM::IXMLDOMNodePtr pCurItemList;
pItemList->reset();
#if !defined(LINUX64)
while ((pCurItemList = pItemList->nextNode()) != NULL)
#else
while ((pCurItemList = pItemList->nextNode()) != 0)
#endif
{
XDOM::IXMLDOMNodeListPtr pItems = pCurItemList->getChildNodes();
XDOM::IXMLDOMNodePtr pCurItem;
pItems->reset();
UINT iCurItem = 1;
#if !defined(LINUX64)
while ((pCurItem = pItems->nextNode()) != NULL)
#else
while ((pCurItem = pItems->nextNode()) != 0)
#endif
{
XDOM::IXMLDOMNodePtr pIType = pCurItem->getAttribute("type");
// if (strcmp(pIType->getText(), "Weapon") == 0)
{
_SmartScriptObject cEntry(GetScriptSystem(), false);
cEntry->SetValue("Type", pIType->getText());
cEntry->SetValue("Name", pCurItem->getName());
#if !defined(LINUX64)
if(pPrimaryWeapon!=NULL)
#else
if(pPrimaryWeapon!=0)
#endif
{
if(strcmp(pPrimaryWeapon->getText(),pCurItem->getName())==0)
{
cEntry->SetValue("Primary", 1);
}
}
cWeaponList->SetAt(iCurItem, *cEntry);
iCurItem++;
cEquipPacks->SetValue(pPackName->getText(), *cWeaponList);
}
}
}
}
_SmartScriptObject cAmmoAvailTable(GetScriptSystem(), false);
XDOM::IXMLDOMNodeListPtr pAmmoTag = pPack->getElementsByTagName("Ammo");
if (pAmmoTag)
{
pAmmoTag->reset();
XDOM::IXMLDOMNodePtr pAmmoTagFirst = pAmmoTag->nextNode();
if (pAmmoTagFirst)
{
XDOM::IXMLDOMNodeListPtr pChildNodes = pAmmoTagFirst->getChildNodes();
XDOM::IXMLDOMNodePtr pAmmo;
pChildNodes->reset();
while (pAmmo = pChildNodes->nextNode())
{
if (pAmmo->getNodeType() == XDOM::NODE_ATTRIBUTE)
{
//TRACE("Ammo: %s = %s", pAmmo->getName(), pAmmo->getText());
cAmmoAvailTable->SetValue(pAmmo->getName(), atoi(pAmmo->getText()));
}
}
}
}
cWeaponList->SetValue("Ammo", *cAmmoAvailTable);
}
RestoreWeaponPacks();
return true;
}
//////////////////////////////////////////////////////////////////////////
void CXGame::SetPlayerEquipPackName(const char *pszPackName)
{
// Pass NULL or "" to remove all equipment from the player
IScriptSystem *pIScriptSystem = GetScriptSystem();
IEntity *pIMyPlayer = (m_pServer != NULL) ? m_pServer->m_pISystem->GetLocalPlayer() :
m_pClient->m_pISystem->GetLocalPlayer();
void *pContainer = NULL;
IEntityContainer *pIContainer = NULL;
CPlayer *pPlayer = NULL;
// Store the name of the equipment pack
IScriptObject *pGlobals=pIScriptSystem->GetGlobalObject();
pGlobals->SetValue("MainPlayerEquipPack", (pszPackName != NULL) ? pszPackName : "");
pGlobals->Release();
if (pIMyPlayer == NULL)
return;
if (pszPackName == NULL || strlen(pszPackName) == 0)
{
// No equipment pack specified, remove all weapons
pIContainer = pIMyPlayer->GetContainer();
if (pIContainer == NULL)
return;
if (pIContainer->QueryContainerInterface(CIT_IPLAYER, &pContainer))
{
pPlayer = (CPlayer *) pContainer;
pPlayer->RemoveAllWeapons();
}
return;
}
// Let the player reload his weapons
pIScriptSystem->BeginCall("BasicPlayer", "InitAllWeapons");
pIScriptSystem->PushFuncParam(pIMyPlayer->GetScriptObject());
pIScriptSystem->PushFuncParam((int)1);
pIScriptSystem->EndCall();
}
//////////////////////////////////////////////////////////////////////////
void CXGame::RestoreWeaponPacks()
{
IEntityIt *pEtyIt = NULL;
IEntity *pICurEty = NULL;
void *pContainer = NULL;
IEntityContainer *pIContainer = NULL;
// start .. temporary checks to find a bug
if(m_pServer)
{
if(!m_pServer->m_pISystem)
{ m_pLog->LogError("CXGame::RestoreWeaponPacks Error1");return; }
}
else
{
if(!m_pClient)
{ m_pLog->LogError("CXGame::RestoreWeaponPacks Error2");return; }
if(!m_pClient->m_pISystem)
{ m_pLog->LogError("CXGame::RestoreWeaponPacks Error3");return; }
}
// end .. temporary checks to find a bug
pEtyIt = (m_pServer ? m_pServer->m_pISystem : m_pClient->m_pISystem)->GetEntities();
while (pICurEty = pEtyIt->Next())
{
pIContainer = pICurEty->GetContainer();
if (pIContainer == NULL)
continue;
if (pIContainer->QueryContainerInterface(CIT_IPLAYER, &pContainer))
{
IScriptSystem *pIScriptSystem = GetScriptSystem();
pIScriptSystem->BeginCall("BasicPlayer", "InitAllWeapons");
pIScriptSystem->PushFuncParam(pICurEty->GetScriptObject());
pIScriptSystem->PushFuncParam((int)1);
pIScriptSystem->EndCall();
}
}
pEtyIt->Release();
}
void CXGame::ReloadWeaponScripts()
{
if (m_pWeaponSystemEx)
{
std::vector<CPlayer*> vPlayers;
CPlayer *pPlayer = NULL;
IEntity *pICurEty = NULL;
IEntityIt *pEtyIt = (m_pServer ? m_pServer->m_pISystem : m_pClient->m_pISystem)->GetEntities();
while (pICurEty = pEtyIt->Next())
{
IEntityContainer *pIContainer = pICurEty->GetContainer();
if (pIContainer == NULL)
continue;
if (pIContainer->QueryContainerInterface(CIT_IPLAYER, (void**) &pPlayer))
{
vPlayers.push_back(pPlayer);
}
}
pEtyIt->Release();
for (std::vector<CPlayer*>::iterator i = vPlayers.begin(); i != vPlayers.end(); ++i)
{
(*i)->SelectWeapon(-1, false);
}
m_pWeaponSystemEx->Reset();
m_pWeaponSystemEx->Init(this, true);
// reload weapons
_SmartScriptObject soWeaponLoadedTable(m_pScriptSystem, true);
if (m_pScriptSystem->GetGlobalValue("WeaponsLoaded", soWeaponLoadedTable))
{
soWeaponLoadedTable->BeginIteration();
while(soWeaponLoadedTable->MoveNext())
{
const char *sClassName;
if (soWeaponLoadedTable->GetCurrentKey(sClassName))
{
CWeaponClass *pWC = m_pWeaponSystemEx->GetWeaponClassByName(sClassName);
if (pWC)
{
pWC->Load();
}
}
}
soWeaponLoadedTable->EndIteration();
}
for (std::vector<CPlayer*>::iterator i = vPlayers.begin(); i != vPlayers.end(); ++i)
{
pPlayer = (*i);
pPlayer->SelectFirstWeapon();
if (!pPlayer->IsMyPlayer())
pPlayer->DrawThirdPersonWeapon(true);
IScriptSystem *pIScriptSystem = GetScriptSystem();
pIScriptSystem->BeginCall("BasicPlayer", "InitAllWeapons");
pIScriptSystem->PushFuncParam(pPlayer->GetEntity()->GetScriptObject());
pIScriptSystem->PushFuncParam((int)1);
pIScriptSystem->EndCall();
}
vPlayers.clear();
}
}

416
CryGame/GameEvents.cpp Normal file
View File

@@ -0,0 +1,416 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameEvents.cpp
//
// History:
// -October 31,2003: created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include "XVehicle.h"
//////////////////////////////////////////////////////////////////////////////////
void EventPlayerCmd::Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream )
{
int iCmdTime = cmd.GetPhysicalTime();
cmd.SetPhysicalTime(iPhysicalTime);
pBitStream->WriteBitStream(stm,idEntity,eEntityId);
cmd.Write(stm,pBitStream,false);
cmd.SetPhysicalTime(iCmdTime);
}
//////////////////////////////////////////////////////////////////////////
void EventPlayerCmd::Read(CStream &stm, int &iPhysicalTime, IBitStream *pBitStream )
{
pBitStream->ReadBitStream(stm,idEntity,eEntityId);
cmd.Read(stm,pBitStream);
iPhysicalTime = cmd.GetPhysicalTime();
}
//////////////////////////////////////////////////////////////////////////
void EventPlayerCmd::Execute(CXGame *pGame)
{
IEntitySystem *pES = pGame->GetSystem()->GetIEntitySystem();
IEntity *pEnt;
CPlayer *pPlayer;
if (pES && (pEnt = pES->GetEntity(idEntity)) && pEnt->GetContainer() &&
pEnt->GetContainer()->QueryContainerInterface(CIT_IPLAYER, (void**)&pPlayer))
pPlayer->ProcessMovements(cmd,true);
}
//////////////////////////////////////////////////////////////////////////
void EventExplosion::Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream )
{
stm.WritePacked((unsigned int)iPhysicalTime);
stm.Write(pos);
stm.Write(damage);
stm.Write(rmin);
stm.Write(rmax);
stm.Write(radius);
stm.Write(impulsivePressure);
stm.Write(shakeFactor);
stm.Write(deafnessRadius);
stm.Write(deafnessTime);
stm.Write(iImpactForceMul);
stm.Write(iImpactForceMulFinal);
stm.Write(iImpactForceMulFinalTorso);
stm.Write(rminOcc);
stm.Write(nOccRes);
stm.Write(nGrow);
pBitStream->WriteBitStream(stm,idShooter,eEntityId);
pBitStream->WriteBitStream(stm,idWeapon,eEntityId);
stm.Write(terrainDefSize);
stm.Write(nTerrainDecalId);
if(nShooterSSID==-1)
stm.Write((uint8)255); // used if ClientID is unknwon
else
stm.Write((uint8)nShooterSSID);
}
//////////////////////////////////////////////////////////////////////////
void EventExplosion::Read(CStream &stm,int &iPhysicalTime, IBitStream *pBitStream )
{
stm.ReadPacked((unsigned int &)iPhysicalTime);
stm.Read(pos);
stm.Read(damage);
stm.Read(rmin);
stm.Read(rmax);
stm.Read(radius);
stm.Read(impulsivePressure);
stm.Read(shakeFactor);
stm.Read(deafnessRadius);
stm.Read(deafnessTime);
stm.Read(iImpactForceMul);
stm.Read(iImpactForceMulFinal);
stm.Read(iImpactForceMulFinalTorso);
stm.Read(rminOcc);
stm.Read(nOccRes);
stm.Read(nGrow);
pBitStream->ReadBitStream(stm,idShooter,eEntityId);
pBitStream->ReadBitStream(stm,idWeapon,eEntityId);
stm.Read(terrainDefSize);
stm.Read(nTerrainDecalId);
uint8 ucId;
stm.Read(ucId);
if(ucId!=255)
nShooterSSID=(int32)ucId; // used if ClientID is unknwon
else
nShooterSSID=-1;
}
//////////////////////////////////////////////////////////////////////////
void EventExplosion::Execute(CXGame *pGame)
{
IEntitySystem *pES = pGame->GetSystem()->GetIEntitySystem();
IEntity *pShooter=pES->GetEntity(idShooter), *pWeapon=pES->GetEntity(idWeapon);
pGame->CreateExplosion(pos,damage,rmin,rmax,radius,impulsivePressure,shakeFactor*(1.0f/254),
deafnessRadius*(20.0f/254),deafnessTime*0.25f,iImpactForceMul,iImpactForceMulFinal,iImpactForceMulFinalTorso,
rminOcc*(1.0f/254),nOccRes,nGrow,pShooter,nShooterSSID,pWeapon,terrainDefSize*(20.0f/254),nTerrainDecalId, true);
}
//////////////////////////////////////////////////////////////////////////
void EventPhysImpulse::Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream )
{
stm.WritePacked((unsigned int)iPhysicalTime);
stm.Write(idPhysEnt);
stm.Write(impulse);
stm.Write(bHasPt);
if (bHasPt)
stm.Write(pt);
stm.Write(bHasMomentum);
if (bHasMomentum)
stm.Write(momentum);
}
//////////////////////////////////////////////////////////////////////////
void EventPhysImpulse::Read(CStream &stm,int &iPhysicalTime, IBitStream *pBitStream )
{
stm.ReadPacked((unsigned int &)iPhysicalTime);
stm.Read(idPhysEnt);
stm.Read(impulse);
stm.Read(bHasPt);
if (bHasPt)
stm.Read(pt);
stm.Read(bHasMomentum);
if (bHasMomentum)
stm.Read(momentum);
}
//////////////////////////////////////////////////////////////////////////
void EventPhysImpulse::Execute(CXGame *pGame)
{
IPhysicalEntity *pPhysEnt = pGame->GetSystem()->GetIPhysicalWorld()->GetPhysicalEntityById(idPhysEnt);
if (pPhysEnt)
{
pe_action_impulse ai;
ai.impulse = impulse;
if (bHasPt)
ai.point = pt;
if (bHasMomentum)
ai.momentum = momentum;
ai.iSource = 3;
pPhysEnt->Action(&ai);
}
}
//////////////////////////////////////////////////////////////////////////
void EventVehicleDamage::Write(CStream &stm,int iPhysicalTime, IBitStream *pBitStream )
{
stm.WritePacked((unsigned int)iPhysicalTime);
pBitStream->WriteBitStream(stm,idVehicle,eEntityId);
stm.Write(damage);
}
//////////////////////////////////////////////////////////////////////////
void EventVehicleDamage::Read(CStream &stm,int &iPhysicalTime, IBitStream *pBitStream )
{
stm.ReadPacked((unsigned int &)iPhysicalTime);
pBitStream->ReadBitStream(stm,idVehicle,eEntityId);
stm.Read(damage);
}
//////////////////////////////////////////////////////////////////////////
void EventVehicleDamage::Execute(CXGame *pGame)
{
IEntitySystem *pES = pGame->GetSystem()->GetIEntitySystem();
IEntity *pEnt;
CVehicle *pVehicle;
if (pES && (pEnt = pES->GetEntity(idVehicle)) && pEnt->GetContainer() &&
pEnt->GetContainer()->QueryContainerInterface(CIT_IVEHICLE, (void**)&pVehicle))
pVehicle->SetEngineHealth(damage*0.5f,true);
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::HasScheduledEvents()
{
return m_lstEvents.size()>0;
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ScheduleEvent(int iPhysTime, BaseEvent *pEvent)
{
if (iPhysTime<0)
{
CXServer *pServer=GetServer();
iPhysTime = SnapTime(m_pSystem->GetIPhysicalWorld()->GetiPhysicsTime());
if(pServer)
iPhysTime += pServer->GetSchedulingDelay();
else
m_pLog->LogError("ScheduleEvent pServer is 0");
}
int nSize=m_lstEvents.size(),iMiddle,iBound[2]={ 0,nSize };
if (iBound[1]>0) do {
iMiddle = (iBound[0]+iBound[1])>>1;
iBound[isneg(iPhysTime-m_lstEvents[iMiddle].iPhysTime)] = iMiddle;
} while(iBound[1]>iBound[0]+1);
for(; iBound[1]<nSize && m_lstEvents[iBound[1]].iPhysTime==iPhysTime; iBound[1]++);
if (iBound[0]<nSize && m_lstEvents[iBound[0]].iPhysTime>iPhysTime)
iBound[1] = iBound[0];
GameEvent event;
event.iPhysTime = iPhysTime;
event.idx = m_iLastCmdIdx++;
(event.pEvent = pEvent)->nRefCount = 1;
m_lstEvents.insert(m_lstEvents.begin()+iBound[1], event);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ScheduleEvent(IEntity *pEnt, CXEntityProcessingCmd &cmd)
{
EventPlayerCmd *pEvent = new EventPlayerCmd;
pEvent->idEntity = pEnt->GetId();
pEvent->cmd = cmd;
pEvent->cmd.ResetTimeSlices();
ScheduleEvent(cmd.GetPhysicalTime(), pEvent);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ScheduleEvent(int iPhysTime, const Vec3& pos,float fDamage,float rmin,float rmax,float radius,float fImpulsivePressure,
float fShakeFactor,float fDeafnessRadius,float fDeafnessTime,
float fImpactForceMul,float fImpactForceMulFinal,float fImpactForceMulFinalTorso,
float rMinOcc,int nOccRes,int nOccGrow, IEntity *pShooter, int shooterSSID, IEntity *pWeapon, float fTerrainDefSize,int nTerrainDecalId)
{
EventExplosion *pEvent = new EventExplosion;
pEvent->pos = pos;
pEvent->damage = fDamage;
pEvent->rmin = rmin;
pEvent->rmax = rmax;
pEvent->radius = radius;
pEvent->impulsivePressure = fImpulsivePressure;
pEvent->shakeFactor = (int)(fShakeFactor*254.0f+0.5f);
pEvent->deafnessRadius = (int)(fDeafnessRadius*(254.0f/20)+0.5f);
pEvent->deafnessTime = (int)(fDeafnessTime*4+0.5f);
pEvent->iImpactForceMul = (int)(fImpactForceMul+0.5f);
pEvent->iImpactForceMulFinal = (int)(fImpactForceMulFinal+0.5f);
pEvent->iImpactForceMulFinalTorso = (int)(fImpactForceMulFinalTorso+0.5f);
pEvent->rminOcc = (int)(rMinOcc*254.0f+0.5f);
pEvent->nOccRes = nOccRes;
pEvent->nGrow = nOccGrow;
pEvent->idShooter = pShooter ? pShooter->GetId() : -1;
pEvent->idWeapon = pWeapon ? pWeapon->GetId() : -1;
pEvent->terrainDefSize = (int)(fTerrainDefSize*(254.0f/20)+0.5f);
pEvent->nTerrainDecalId = nTerrainDecalId;
pEvent->nShooterSSID=shooterSSID;
ScheduleEvent(iPhysTime,pEvent);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ScheduleEvent(int iPhysTime, IEntity *pVehicle,float fDamage)
{
EventVehicleDamage *pEvent = new EventVehicleDamage;
pEvent->idVehicle = pVehicle->GetId();
pEvent->damage = (int)(fDamage*2+0.5f);
ScheduleEvent(iPhysTime, pEvent);
}
////
void CXGame::ScheduleEvent(int iPhysTime, IPhysicalEntity *pPhysEnt,pe_action_impulse *pai)
{
EventPhysImpulse *pEvent = new EventPhysImpulse;
pEvent->idPhysEnt = m_pSystem->GetIPhysicalWorld()->GetPhysicalEntityId(pPhysEnt);
pEvent->impulse = pai->impulse;
if (pEvent->bHasPt = !is_unused(pai->point))
pEvent->pt = pai->point;
if (pEvent->bHasMomentum = !is_unused(pai->momentum))
pEvent->momentum = pai->momentum;
ScheduleEvent(iPhysTime, pEvent);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ExecuteScheduledEvents()
{
int iCurTime=SnapTime(m_pSystem->GetIPhysicalWorld()->GetiPhysicsTime());
size_t i, sz = m_lstEvents.size();
for(i=0; i<sz && m_lstEvents[i].iPhysTime <= iCurTime; ++i)
{
if (m_lstEvents[i].iPhysTime<iCurTime)
m_pLog->Log("Event missed the schedule by %.4f",
(iCurTime-m_lstEvents[i].iPhysTime)*m_pSystem->GetIPhysicalWorld()->GetPhysVars()->timeGranularity);
m_lstEvents[i].pEvent->Execute(this);
}
if (i)
m_lstEvents.erase(m_lstEvents.begin(),m_lstEvents.begin()+i);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::WriteScheduledEvents(CStream &stm, int &iLastEventWritten, int iTimeDelta)
{
IBitStream *pBitStream=GetIBitStream();
unsigned int i,sz;
int iLastEventCur = -1;
for(i=sz=0; i<m_lstEvents.size(); i++)
sz += m_lstEvents[i].idx>iLastEventWritten;
stm.Write((short)sz);
if (sz>0)
{
for(i=0; i<m_lstEvents.size(); i++)
if (m_lstEvents[i].idx>iLastEventWritten)
{
stm.WriteNumberInBits(m_lstEvents[i].pEvent->GetType(),2);
m_lstEvents[i].pEvent->Write(stm,m_lstEvents[i].iPhysTime+iTimeDelta,pBitStream);
iLastEventCur = max(iLastEventCur, m_lstEvents[i].idx);
}
iLastEventWritten = iLastEventCur;
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ReadScheduledEvents(CStream &stm)
{
IBitStream *pBitStream=GetIBitStream();
short nEvents;
stm.Read(nEvents);
for(int i=0; i<nEvents; i++)
{
int iType=0; stm.ReadNumberInBits(iType,2);
BaseEvent *pEvent;
switch (iType)
{
case EVENT_MOVECMD: pEvent = new EventPlayerCmd; break;
case EVENT_EXPLOSION: pEvent = new EventExplosion; break;
case EVENT_IMPULSE: pEvent = new EventPhysImpulse; break;
case EVENT_VEHDAMAGE: pEvent = new EventVehicleDamage;
}
int iPhysTime;
pEvent->Read(stm,iPhysTime,pBitStream);
ScheduleEvent(iPhysTime,pEvent);
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::AdvanceReceivedEntities(int iPhysicalWorldTime)
{
m_bSynchronizing = true;
IPhysicalWorld *pWorld = GetSystem()->GetIPhysicalWorld();
//m_pLog->LogToConsole("client time step %.3f",(pWorld->GetiPhysicsTime()-m_iPhysicalWorldTime)*pWorld->GetPhysVars()->timeGranularity);
float timeGran=pWorld->GetPhysVars()->timeGranularity, fixedStep=g_MP_fixed_timestep->GetFVal(), fStep;
int iPrevTime=pWorld->GetiPhysicsTime(), iStep=GetiFixedStep();
if (iPrevTime>iPhysicalWorldTime)
{
if (UseFixedStep())
{
pWorld->SetiPhysicsTime(SnapTime(iPhysicalWorldTime));
int i = SnapTime(iPrevTime)-SnapTime(iPhysicalWorldTime);
if (i>iStep*20)
{
m_pLog->LogToConsole("Client catch-up step is too big (%.4f)",i*timeGran);
i = iStep*20;
}
for(; i>0; i-=iStep)
{
//m_pGame->ExecuteScheduledEvents();
pWorld->TimeStep(fixedStep, ent_rigid|ent_flagged_only);
}
pWorld->SetiPhysicsTime(iPhysicalWorldTime);
fStep = min(fixedStep*20, (iPrevTime-iPhysicalWorldTime)*timeGran);
do {
pWorld->TimeStep(min(fStep,0.1f), ent_living|ent_independent|ent_flagged_only);
} while ((fStep-=0.1f)>0.0001f);
}
else
{
fStep = min(0.3f, (pWorld->GetiPhysicsTime()-iPhysicalWorldTime)*timeGran);
do {
pWorld->TimeStep(min(fStep,0.1f), ent_all|ent_flagged_only);
} while ((fStep-=0.1f)>0.0001f);
}
pWorld->SetiPhysicsTime(iPrevTime);
}
else
pWorld->SetiPhysicsTime(iPhysicalWorldTime);
m_bSynchronizing = false;
}

3011
CryGame/GameLoading.cpp Normal file

File diff suppressed because it is too large Load Diff

153
CryGame/GameMemStats.cpp Normal file
View File

@@ -0,0 +1,153 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <crysizer.h>
#include "Game.h"
#include "TagPoint.h"
#include "XSurfaceMgr.h"
#include "EntityClassRegistry.h"
#include "XServer.h"
#include "XServerSlot.h"
#include "XPlayer.h"
#include "XPuppetProxy.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include "ScriptObjectLanguage.h"
#include "ScriptObjectPlayer.h"
#include "ScriptObjectSpectator.h"
#include "ScriptObjectVehicle.h"
#include "ScriptObjectStream.h"
#include "ScriptObjectAI.h"
#include "ScriptObjectBoids.h"
//////////////////////////////////////////////////////////////////////////
void CXGame::GetMemoryStatistics(ICrySizer *pSizer)
{
unsigned size;
pSizer->AddObject( this, sizeof *this );
pSizer->AddObject( &m_EntityClassRegistry, m_EntityClassRegistry.MemStats() );
pSizer->AddObject( &m_XAreaMgr, m_XAreaMgr.MemStat() );
pSizer->AddObject( &m_XDemoMgr, sizeof(m_XDemoMgr) );
TagPointMap::iterator tpItr = m_mapTagPoints.begin();
for(size=0;tpItr!=m_mapTagPoints.end();tpItr++)
{
size += (tpItr->first).capacity();
size += (tpItr->second)->MemStats();
}
pSizer->AddObject(&m_mapTagPoints, size);
pSizer->AddObject(&m_XSurfaceMgr, m_XSurfaceMgr.MemStat());
if(m_pServer)
pSizer->AddObject(m_pServer, m_pServer->MemStats());
if(m_pClient)
pSizer->AddObject(m_pClient, sizeof( *m_pClient ) );
pSizer->AddObject( m_pScriptObjectGame, sizeof *m_pScriptObjectGame);
pSizer->AddObject( m_pScriptObjectInput, sizeof *m_pScriptObjectInput);
pSizer->AddObject( m_pScriptObjectBoids, sizeof *m_pScriptObjectBoids);
pSizer->AddObject( m_pScriptObjectLanguage, sizeof *m_pScriptObjectLanguage);
pSizer->AddObject( m_pScriptObjectAI, sizeof *m_pScriptObjectAI);
size=0;
for(ActionsEnumMap::iterator aItr=m_mapActionsEnum.begin(); aItr!=m_mapActionsEnum.end(); aItr++)
{
size += (aItr->first).capacity();
size += sizeof( ActionInfo );
ActionInfo *curA = &(aItr->second);
size += curA->sDesc.capacity();
for(unsigned int i=0; i< curA->vecSetToActionMap.size(); i++)
size += curA->vecSetToActionMap[i].capacity();
}
pSizer->AddObject( &m_mapActionsEnum, size);
if(m_pWeaponSystemEx)
pSizer->AddObject( m_pWeaponSystemEx, m_pWeaponSystemEx->MemStats());
size = 0;
IEntityIt *eItr=m_pSystem->GetIEntitySystem()->GetEntityIterator();
IEntity* ent;
while((ent=eItr->Next())!=NULL)
{
IEntityContainer *pCnt=ent->GetContainer();
CPlayer *pPlayer = NULL;
if(pCnt)
{
pCnt->QueryContainerInterface(CIT_IPLAYER,(void **) &pPlayer);
if( pPlayer )
size += pPlayer->MemStats();
}
}
pSizer->AddObject( "players from entSystem", size);
}
//////////////////////////////////////////////////////////////////////////
unsigned CTagPoint::MemStats()
{
unsigned memSize = sizeof *this;
memSize += m_sName.capacity();
return memSize;
}
//////////////////////////////////////////////////////////////////////////
unsigned CXSurfaceMgr::MemStat()
{
unsigned size = sizeof *this;
for(PhysicalSurfecesMapItor pmi=m_mapPhysSurfaces.begin(); pmi!=m_mapPhysSurfaces.end(); pmi++)
size += (pmi->second).capacity() + sizeof(int);
for(MaterialsMapItor mmi=m_mapMaterials.begin(); mmi!=m_mapMaterials.end(); mmi++)
size += (mmi->first).capacity() + sizeof(int);
for(MaterialsNamesMapItor mni=m_mapMaterialsNames.begin(); mni!=m_mapMaterialsNames.end(); mni++)
{
MatDesc &mdesc = mni->second;
size += (mni->first).capacity() + mdesc.sScriptFilename.capacity() + sizeof(mdesc);
}
return size;
}
//////////////////////////////////////////////////////////////////////////
unsigned CEntityClassRegistry::MemStats()
{
unsigned size = sizeof *this;
for(EntityClassMapItor itr=m_vEntityClasses.begin(); itr!=m_vEntityClasses.end(); itr++)
{
size += sizeof(EntityClass) + (itr->second).strFullScriptFile.capacity()
+ (itr->second).strScriptFile.capacity()
+ (itr->second).strClassName.capacity();
}
return size;
}
//////////////////////////////////////////////////////////////////////////
unsigned CXServerSlot::MemStats()
{
unsigned size = sizeof *this;
size += m_strPlayerName.capacity();
size += m_strPlayerModel.capacity();
return size;
}
//////////////////////////////////////////////////////////////////////////
unsigned CPlayer::MemStats()
{
unsigned size = sizeof *this;
size += m_mapPlayerWeapons.size()*(sizeof(WeaponInfo) + sizeof(int) + sizeof(WeaponInfo*) );
size += sizeof(CXPuppetProxy);
return size;
}

460
CryGame/GameMisc.cpp Normal file
View File

@@ -0,0 +1,460 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameMisc.cpp
//
// History:
// -October 31,2003: created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include "ScriptObjectBoids.h"
#include "Flock.h"
#include "WeaponClass.h"
#include "ScriptObjectRenderer.h"
#include "ScriptTimerMgr.h"
//////////////////////////////////////////////////////////////////////////
void CXGame::EnableUIOverlay(bool bEnable, bool bExclusiveInput)
{
if (!m_bEditor)
{
m_bUIOverlay = bEnable;
if ((bExclusiveInput) && (!m_bUIExclusiveInput))
{
m_pIActionMapManager->Disable();
m_pSystem->GetIInput()->SetExclusiveListener(m_pUISystem);
m_bUIExclusiveInput = 1;
}
else if ((!bExclusiveInput) && (m_bUIExclusiveInput))
{
m_pIActionMapManager->Enable();
m_pSystem->GetIInput()->SetExclusiveListener(0);
m_bUIExclusiveInput = 0;
}
}
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::IsUIOverlay()
{
return m_bUIOverlay;
}
//////////////////////////////////////////////////////////////////////////
//! Check if a sound is potentially hearable (used to check if loading a dialog is needed)
bool CXGame::IsSoundPotentiallyHearable(Vec3d &SoundPos, float fClipRadius)
{
ASSERT(m_pSystem);
ISoundSystem *pSoundSystem=m_pSystem->GetISoundSystem();
if (!pSoundSystem)
return false;
if (pSoundSystem->UsingDirectionalAttenuation())
return true;
CCamera &Cam=m_pSystem->GetViewCamera();
float fDist=(Cam.GetPos()-SoundPos).GetLengthSquared();
if (fDist<fClipRadius)
return true;
return false;
}
//////////////////////////////////////////////////////////////////////
//! Retrieve the server-rules.
CXServerRules* CXGame::GetRules() const
{
if (m_pServer)
return m_pServer->GetRules();
// if not server.
return 0;
}
//////////////////////////////////////////////////////////////////////
//!Force the view camera of the player
//!
//!(NOTE: this function is here because the editor needs it here)
void CXGame::SetViewAngles(const Vec3d &angles)
{
if (m_pClient)
m_pClient->m_PlayerProcessingCmd.SetDeltaAngles(angles);
}
//////////////////////////////////////////////////////////////////////
//! Retrieve the local player-entity
IEntity *CXGame::GetMyPlayer()
{
if (m_pClient)
return m_pClient->m_pISystem->GetLocalPlayer();
return NULL;
}
//////////////////////////////////////////////////////////////////////////
//! Selects the current UI (hud etc.)
void CXGame::SetCurrentUI(CUIHud *pUI)
{
if (pUI!=m_pCurrentUI) // new ui has been selected
{
// shutdown the old one
if (m_pCurrentUI)
m_pCurrentUI->ShutDown();
// init the new one
m_pCurrentUI = pUI;
m_pCurrentUI->Init(m_pScriptSystem);
}
}
// changes in and out of third person
//////////////////////////////////////////////////////////////////////////
void CXGame::SetViewMode(bool bThirdPerson)
{
if (GetMyPlayer())
{
CPlayer *pPlayer;
if (GetMyPlayer()->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void**)&pPlayer))
{
// prevent player from going into third person mode when he is aiming
if (pPlayer->m_stats.aiming)
return;
// disable third person view when not in vehicle AND not in devmode
if(!IsDevModeEnable() && bThirdPerson && !pPlayer->GetVehicle())
return;
/*
if (pPlayer->GetVehicle() && bThirdPerson)
{
// do not allow the player to switch to 3rd person
// mode when driving a vehicle
return;
}
*/
pPlayer->m_bFirstPerson = !bThirdPerson;
// don't hide player - need to call CPlayer::OnDraw always for mounted weapons
// use pPlayer->m_bFirstPerson to not draw player
// if (bThirdPerson)
pPlayer->GetEntity()->DrawCharacter(0,ETY_DRAW_NORMAL);
// else
// pPlayer->GetEntity()->DrawCharacter(0,ETY_DRAW_NONE);
pPlayer->SetViewMode(bThirdPerson);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::HideLocalPlayer( bool hide,bool bEditor )
{
m_bHideLocalPlayer = hide;
if (GetMyPlayer())
{
CPlayer *pPlayer;
if (GetMyPlayer()->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void**)&pPlayer))
{
// [Marco K] weapons are now drawn through the player Entity
if(pPlayer->GetSelectedWeapon()){
if(hide){
pPlayer->GetEntity()->DrawCharacter(1, 0);
}
else{
pPlayer->GetEntity()->DrawCharacter(1, CS_FLAG_DRAW_NEAR);
}
}
if (!bEditor)
{
// Dont do this in editor.
pPlayer->GetEntity()->EnablePhysics(!hide);
if (!hide)
{
// Force player positin on physics if it was desynced.
Vec3 pos = pPlayer->GetEntity()->GetPos();
pPlayer->GetEntity()->SetPos(pos+Vec3(0,0,0.1f)); // Force change of position.
pPlayer->GetEntity()->SetPos(pos);
}
}
// hide actual player
if(hide)
{
pPlayer->GetEntity()->DrawCharacter(0,0);
}
else //if (!pPlayer->IsFirstPerson())
pPlayer->SetViewMode(!pPlayer->IsFirstPerson());
//GetEntity()->DrawCharacter(0,1);
}
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::ReloadScripts()
{
// includes the physical material properties (e.g. friction)
m_XSurfaceMgr.ReloadMaterials();
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnSetVar(ICVar *pVar)
{
IXSystem *pS=GetXSystem();
if (pS && IsMultiplayer())
pS->OnSetVar(pVar);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::CreateExplosion(const Vec3& pos,float fDamage,float rmin,float rmax,float radius,float fImpulsivePressure,
float fShakeFactor,float fDeafnessRadius,float fDeafnessTime,
float fImpactForceMul,float fImpactForceMulFinal,float fImpactForceMulFinalTorso,
float rMinOcc,int nOccRes,int nOccGrow, IEntity *pShooter, int shooterSSID, IEntity *pWeapon,
float fTerrainDefSize,int nTerrainDecalId, bool bScheduled)
{
if (!bScheduled && IsMultiplayer() && UseFixedStep())
{
if (IsServer())
ScheduleEvent(-1, pos,fDamage,rmin,rmax,radius,fImpulsivePressure,fShakeFactor,fDeafnessRadius,fDeafnessTime,fImpactForceMul,
fImpactForceMulFinal,fImpactForceMulFinalTorso,rMinOcc,nOccRes,nOccGrow, pShooter,shooterSSID,pWeapon, fTerrainDefSize,nTerrainDecalId);
return;
}
IPhysicalWorld *pWorld = m_pSystem->GetIPhysicalWorld();
int iTypes = ent_rigid|ent_sleeping_rigid|ent_living;
if (m_pSystem->GetIConsole()->GetCVar("physics_quality")->GetIVal()>=2)
iTypes |= ent_independent;
//simulate the first explosion only for applying damage(0 as impulse and -1 as occlusion res)
// [Anton] the first explosion is a normal one: it builds occlusion map and applies impulse
pWorld->SimulateExplosion(pos,pos, rmin,rmax,rmin, fImpulsivePressure, nOccRes,nOccGrow,rMinOcc, 0,0, iTypes);
float force = fDamage*.0173f;
float falloff, curDamage;
if( force > 2.0f )
force = 2.0f;
m_pSystem->GetI3DEngine()->ApplyForceToEnvironment(pos,radius,force);
IPhysicalEntity **ppList = NULL;
int iNumEntites;
int i;
IEntity *pIEntity = NULL;
vectorf vMin(pos.x - radius, pos.y - radius, pos.z - radius);
vectorf vMax(pos.x + radius, pos.y + radius, pos.z + radius);
_SmartScriptObject pGR(m_pScriptSystem,true);
m_pScriptSystem->GetGlobalValue("GameRules",*pGR);
//////////////////////////////////////////////////////////////////////////
// Check independent entities.
//////////////////////////////////////////////////////////////////////////
ppList = NULL;
iNumEntites = pWorld->GetEntitiesInBox(vMin, vMax, ppList, ent_independent|ent_allocate_list);
for (i=0; i<iNumEntites; i++)
{
int physType = ppList[i]->GetiForeignData();
if (physType == OT_BOID)
{
// Check if boid hit.
CBoidObject *pBoid = (CBoidObject*)ppList[i]->GetForeignData(OT_BOID);
if (pBoid)
{
string surfaceName;
pBoid->Kill( pos,(pBoid->m_pos-pos)*10.0f,surfaceName );
}
}
}
pWorld->GetPhysUtils()->DeletePointer(ppList);
//////////////////////////////////////////////////////////////////////////
ppList = NULL;
iNumEntites = pWorld->GetEntitiesInBox(vMin, vMax, ppList, (ent_all&~(ent_terrain|ent_independent))|ent_allocate_list);
for (i=0; i<iNumEntites; i++)
{
pIEntity = (IEntity *) ppList[i]->GetForeignData();
if (!pIEntity)
{
continue;
}
// to take big objects into account be measure the distance to the bounding sphere surface
float fPhyEntityRad = pIEntity->GetRadiusPhys();
float fDistance = (pos - pIEntity->GetPos()).Length()-fPhyEntityRad;
if(fDistance<0)
fDistance=0; // the objects interpenetrate
if (fDistance > radius)
continue;
falloff = 1.0f - fDistance / radius;
curDamage = fDamage*falloff;
Vec3 bbox[2]; pIEntity->GetBBox(bbox[0],bbox[1]);
Vec3 dir=(bbox[0]+bbox[1])*0.5f-pos;//pIEntity->GetPos()-pos;
dir.Normalize();
CScriptObjectVector oDir(m_pScriptSystem),oPos(m_pScriptSystem);
oDir=dir; oPos=pIEntity->GetPos();
// send DEAFENED event is needed...
if (fDeafnessRadius>0.0f)
{
float fDeafenedTime=fDeafnessTime*(1.0f-fDistance/fDeafnessRadius);;
_SmartScriptObject pObj(m_pScriptSystem);
pObj->SetValue("fTime", fDeafenedTime);
pIEntity->SendScriptEvent(ScriptEvent_Deafened, *pObj);
}
// send DAMAGE event
_SmartScriptObject pTable(m_pScriptSystem);
if (pWeapon)
pTable->SetValue("weapon",pWeapon->GetScriptObject());
if (pIEntity->GetScriptObject())
pTable->SetValue("target",pIEntity->GetScriptObject());
pTable->SetValue( "explosion",true );
if (pShooter && !IsMultiplayer()) // in Multiplayer it's not save to send the shooter - the EntityId might be reused already
pTable->SetValue("shooter",pShooter->GetScriptObject());
if(shooterSSID!=-1) // -1 means unknown ClientID
pTable->SetValue("shooterSSID",shooterSSID); // in Multiplayer this is the save way to get the shooter
pTable->SetValue("dir",*oDir);
pTable->SetValue("damage",curDamage);
pTable->SetValue("damage_type", "normal");
pTable->SetValue("weapon_death_anim_id", 0);
pTable->SetValue("pos",*oPos);
pTable->SetValue("ipart", -1);
pTable->SetValue("impact_force_mul",fImpactForceMul*falloff);
pTable->SetValue("impact_force_mul_final",fImpactForceMulFinal*falloff);
pTable->SetValue("impact_force_mul_final_torso",fImpactForceMulFinalTorso*falloff);
//_SmartScriptObject pMat(m_pScriptSystem, true);
//if (m_pScriptSystem->GetGlobalValue("mat_flesh", pMat))
IScriptObject *pMat = NULL;
pMat = m_XSurfaceMgr.GetMaterialByName("mat_flesh");
if (pMat)
pTable->SetValue("target_material", pMat);
pIEntity->OnDamage(pTable);
}
pWorld->GetPhysUtils()->DeletePointer(ppList);
//
//shake the camera from explosion
pIEntity = GetMyPlayer();
if( pIEntity )
{
CPlayer* pPlayer=NULL;
CXClient *pClient=GetClient();
if (pIEntity->GetContainer())
pIEntity->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void**) &pPlayer);
if(pPlayer && pClient)
{
// float distCoeff = damage/(pIEntity->GetPos()-pos).Length();
// float distCoeff = damage*(1.0f - (pIEntity->GetPos()-pos).Length()*pClient->cl_explShakeDCoef->GetFVal());
float distCoeff = (1.0f - (pIEntity->GetPos()-pos).Length()*pClient->cl_explShakeDCoef);
if( distCoeff>1.0f )
distCoeff = 1.0f;
if( distCoeff>0.0f )
{
distCoeff *= fShakeFactor;
pPlayer->SetShakeL( Vec3(fDamage*distCoeff*pClient->cl_explShakeAmplH,
fDamage*distCoeff*pClient->cl_explShakeAmplH,
fDamage*distCoeff*pClient->cl_explShakeAmplV),
Vec3(pClient->cl_explShakeFreq, pClient->cl_explShakeFreq, pClient->cl_explShakeFreq),
distCoeff*pClient->cl_explShakeTime);
}
}
}
//simulate the explosion for adding impulse .
// [Anton] the 2nd explosion has nOccRes=-1, meaning it will reuse the occlusion map from the previous explosion
// and add impulse only to the objects that were not affected by the previous explosion
pWorld->SimulateExplosion(pos,pos, rmin, rmax, rmin, fImpulsivePressure, -1,nOccGrow,rMinOcc, 0,0,iTypes);
if (fTerrainDefSize>0)
{
bool bDeform = false;
//check if e_deformable_terrain for some reason is NULL, maybe at the init time it wasnt already created.
if (!e_deformable_terrain)
e_deformable_terrain = m_pSystem->GetIConsole()->GetCVar("e_deformable_terrain");
// always make it false, when e_deformable_terrain is set to 0
if (e_deformable_terrain)
bDeform = e_deformable_terrain->GetIVal()!=0?true:false;
Vec3d vHitDir = (pShooter->GetPos() - pos).GetNormalized();
m_pSystem->GetI3DEngine()->OnExplosion(pos,vHitDir,fTerrainDefSize,nTerrainDecalId,bDeform);
}
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::GoreOn() const
{
return (g_Gore->GetIVal()==2);
}
//////////////////////////////////////////////////////////////////////////
IBitStream *CXGame::GetIBitStream()
{
if(IsMultiplayer())
return &m_BitStreamCompressed;
return &m_BitStreamBase;
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::ExecuteScript(const char *sPath,bool bForceReload)
{
string temp=sPath;
string::size_type n;
n=temp.find("$GT$");
if(n!=string::npos){
temp.replace(n,4,g_GameType->GetString());
if(!m_pScriptSystem->ExecuteFile(temp.c_str(),false,bForceReload))
{
temp=sPath;
temp.replace(n,4,"Default");
return m_pScriptSystem->ExecuteFile(temp.c_str(),true,bForceReload);
}
return true;
}
//no special path
return m_pScriptSystem->ExecuteFile(sPath,true);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::OnCollectUserData(INT_PTR nValue,int nCookie) //AMD Port
{
switch(nCookie){
case USER_DATA_SCRIPTOBJRENDERER:{
CScriptObjectRenderer *pSS=(CScriptObjectRenderer *)nValue;
delete pSS;
}
break;
default:
break;
}
}
//////////////////////////////////////////////////////////////////////////
int CXGame::AddTimer(IScriptObject *pTable,unsigned int nStartTimer,unsigned int nTimer,IScriptObject *pUserData,bool bUpdateDuringPause)
{
return (m_pScriptTimerMgr->AddTimer(pTable,nStartTimer,nTimer,pUserData,bUpdateDuringPause));
}

424
CryGame/GameMods.cpp Normal file
View File

@@ -0,0 +1,424 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001-2004.
// -------------------------------------------------------------------------
// File name: GameMods.cpp
// Version: v1.00
// Created: 13/1/2004 by Timur.
// Compilers: Visual Studio.NET 2003
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "GameMods.h"
#include <ICryPak.h>
#include "Game.h"
#if defined(LINUX)
#include <sys/io.h>
#else
# include <io.h>
#endif
//////////////////////////////////////////////////////////////////////////
CGameMods::CGameMods( CXGame *pGame )
{
m_pGame = pGame;
m_pSystem = pGame->GetSystem();
m_pILog=m_pSystem->GetILog();
m_pMod=NULL;
m_sCurrentMod=string("FarCry");
ScanMods();
}
//////////////////////////////////////////////////////////////////////////
CGameMods::~CGameMods()
{
ClearMods();
}
//////////////////////////////////////////////////////////////////////////
void CGameMods::ClearMods()
{
for (int i = 0; i < (int)(m_mods.size()); i++)
{
CloseMod(m_mods[i]);
delete m_mods[i];
}
m_mods.clear();
}
//////////////////////////////////////////////////////////////////////////
SGameModDescription* CGameMods::Find( const char *sModName ) const
{
// Find this mod.
for (int i = 0; i < (int)(m_mods.size()); i++)
{
if (stricmp(sModName,m_mods[i]->sName.c_str()) == 0)
{
return m_mods[i];
}
}
return NULL;
}
//////////////////////////////////////////////////////////////////////////
const SGameModDescription* CGameMods::GetModDescription( const char *sModName ) const
{
return Find( sModName );
}
//////////////////////////////////////////////////////////////////////////
const char* CGameMods::GetCurrentMod() const
{
return m_sCurrentMod.c_str();
}
//////////////////////////////////////////////////////////////////////////
void CGameMods::CloseMod(SGameModDescription *pMod)
{
if (pMod)
{
// remove mod folder from crypak
string sMOD=string("Mods/")+pMod->sName;
m_pSystem->GetIPak()->RemoveMod(sMOD.c_str());
// close language pack
ICVar *pLanguage=m_pSystem->GetIConsole()->GetCVar("g_language");
if (pLanguage && pLanguage->GetString())
{
char szPakName[512];
sprintf(szPakName,"Mods/%s/%s/Localized/%s.pak",m_sCurrentMod.c_str(),DATA_FOLDER,pLanguage->GetString());
m_pSystem->GetIPak()->ClosePack(szPakName);
}
// close paks in the root
string sModPacks=sMOD+"/"+string("*.pak");
m_pSystem->GetIPak()->ClosePacks(sMOD.c_str());
// close basic packs
sModPacks=sMOD+"/"+string(DATA_FOLDER)+"/*.pak";
m_pSystem->GetIPak()->ClosePacks(sMOD.c_str());
}
}
//////////////////////////////////////////////////////////////////////////
bool CGameMods::SetCurrentMod(const char *sModName,bool bNeedsRestart)
{
ASSERT(sModName);
#if defined(LINUX)
RemoveCRLF(sModName);
#endif
if (stricmp(m_sCurrentMod.c_str(),sModName)==0)
{
m_pILog->Log("MOD %s already loaded",sModName);
return (true); // already set
}
// remove the previous mod (if any)
CloseMod(m_pMod);
m_pMod=NULL;
m_sCurrentMod.clear();
bool bNormalGame=false;
if ((stricmp(sModName,"FarCry")==0))
bNormalGame=true;
m_pILog->Log("Loading MOD %s",sModName);
// switch back to normal farcry
if (bNormalGame)
{
if (!m_pGame->m_bEditor)
{
if (bNeedsRestart)
{
// realunch if changing at runtime back to FC - since no new paks
// should be loaded
m_sCurrentMod=string(sModName);
m_pGame->SendMessage("Relaunch");
return (true);
}
// it is already set - this can happen only when returning to normal
// FC after another mod was loaded - so it is already set
return (true);
}
else
{
// TODO: all previous packs are closed now, editor should reload
// the level and other stuff if necessary
return (true);
}
}
// We're trying to set a MOD which is not normal farcry.
// Find this mod.
m_pMod = Find( sModName );
if (!m_pMod)
{
// mod not found - keep the current one
//m_sCurrentMod.clear();
return (false);
}
m_sCurrentMod = m_pMod->sName;
if (!m_pGame->m_bEditor && bNeedsRestart)
{
// in game mode, after changing mod runtime, always relaunch to assure
// everything, including dlls, gets reloaded
// if bNeedsRestart if false, it means the game was launched with
// command line MOD (best/preferred way)
m_pILog->Log("New MOD set - relaunching game");
m_pGame->SendMessage("Relaunch");
return (true);
}
// make the crypak system aware of the new MOD
m_sCurrentMod = sModName;
// Open the language pack directly from the MOD folder
ICVar *pLanguage=m_pSystem->GetIConsole()->GetCVar("g_language");
if (pLanguage && pLanguage->GetString())
{
char szPakName[512];
sprintf(szPakName,"Mods/%s/%s/Localized/%s.pak",m_sCurrentMod.c_str(),DATA_FOLDER,pLanguage->GetString());
m_pSystem->GetIPak()->OpenPack( "",szPakName );
}
string sMOD=string("Mods/")+sModName;
m_pSystem->GetIPak()->AddMod(sMOD.c_str());
// Open all paks in the mod folder.
char sPaksFilter[_MAX_PATH];
_makepath( sPaksFilter,NULL,m_pMod->sFolder.c_str(),"*","pak" );
m_pSystem->GetIPak()->OpenPacks( "",sPaksFilter );
// Open all basic *.pak files in the MOD folder
string paksmodFolder = string("Mods/")+string(m_sCurrentMod)+"/"+string(DATA_FOLDER)+"/*.pak";
m_pSystem->GetIPak()->OpenPacks( "",paksmodFolder.c_str() );
//////////////////////////////////////////////////////////////////////////
// Reload materials.
/*
// this is unsupported for now
if (m_pGame->m_bEditor)
{
// TODO: Editor should reload the level
m_pGame->m_XSurfaceMgr.LoadMaterials( "Scripts/Materials",true,true );
}
*/
//////////////////////////////////////////////////////////////////////////
return true;
}
// extract value from a text, should be included between ""
//////////////////////////////////////////////////////////////////////////
bool CGameMods::GetValue(const char *szKey,const char *szText,char *szRes)
{
// find the key
const char *szStart=strstr(szText,szKey);
if (!szStart)
return (false);
// find the starting point
const char *szValueStart=strstr(szStart,"\"");
if (!szValueStart)
return (false);
const char *szCurr=szValueStart+1; // skip "
// get the string
while (*szCurr && *szCurr!='"')
{
*szRes++=*szCurr++;
}
if (*szCurr!='"')
return (false);
*szRes=0;
return (true);
}
// gets all needed info from the mod desc text file
//////////////////////////////////////////////////////////////////////////
bool CGameMods::ParseModDescription(const char *szFolder,SGameModDescription*pMod)
{
char szFilename[256];
sprintf(szFilename,"%s/ModDesc.txt",szFolder);
ICryPak *pIPak = m_pSystem->GetIPak();
FILE *pFile=pIPak->FOpen(szFilename,"rb");
if (!pFile)
return (false);
// read the mod desc in a buffer
pIPak->FSeek(pFile, 0, SEEK_END);
int nSize = pIPak->FTell(pFile);
pIPak->FSeek(pFile, 0, SEEK_SET);
if (nSize==0)
{
pIPak->FClose(pFile);
return (false);
}
char *pBuffer;
pBuffer = new char[nSize+1];
if (pIPak->FRead(pBuffer, nSize, 1, pFile) == 0)
{
delete [] pBuffer;
pIPak->FClose(pFile);
return (false);
}
pIPak->FClose(pFile);
pBuffer[nSize]=0; // null terminate the string
// extract info
char *pBufferTemp = new char[nSize+1];
if (GetValue("_Title_",pBuffer,pBufferTemp))
pMod->sTitle=string(pBufferTemp);
if (GetValue("_Author_",pBuffer,pBufferTemp))
pMod->sAuthor=string(pBufferTemp);
if (GetValue("_Version_",pBuffer,pBufferTemp))
pMod->version.Set(pBufferTemp);
if (GetValue("_Website_",pBuffer,pBufferTemp))
pMod->sWebsite=string(pBufferTemp);
if (GetValue("_Description_",pBuffer,pBufferTemp))
pMod->sDescription=string(pBufferTemp);
delete [] pBuffer;
delete [] pBufferTemp;
return (true);
}
//////////////////////////////////////////////////////////////////////////
void CGameMods::ScanMods()
{
// delete previous mods
ClearMods();
// search all files in the mods folder
struct _finddata_t c_file;
intptr_t hFile;
string sSearchPattern = "Mods/*.*";
ICryPak *pIPak = m_pSystem->GetIPak();
if ((hFile = pIPak->FindFirst(sSearchPattern.c_str(),&c_file)) == -1L )
return;
do
{
// skip files and ., .., keep only real folders
if ((c_file.attrib &_A_SUBDIR) && ((strncmp(c_file.name,".",1)!=0)))
{
m_pILog->Log("Found MOD game: %s",c_file.name);
if (stricmp(c_file.name,"FarCry")==0)
continue;
SGameModDescription *pGameMod=new SGameModDescription;
pGameMod->sName=c_file.name;
pGameMod->sFolder=string("Mods/")+c_file.name;
if (!ParseModDescription(pGameMod->sFolder.c_str(),pGameMod))
{
pGameMod->sAuthor=string("Unknown");
pGameMod->sTitle=string("No Title");
}
m_mods.push_back(pGameMod);
}
} while(pIPak->FindNext( hFile, &c_file ) == 0);
pIPak->FindClose( hFile );
}
//////////////////////////////////////////////////////////////////////////
const char *CGameMods::GetModPath(const char *szSource)
{
if (m_sCurrentMod.empty() || (stricmp(m_sCurrentMod.c_str(),"FarCry")==0))
return (NULL);
m_sReturnPath=string("Mods/")+m_sCurrentMod+"/"+string(szSource);
return (m_sReturnPath.c_str());
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::OpenPacks(const char *szFolder)
{
// open first packs in the farcry folder
bool bFound=m_pSystem->GetIPak()->OpenPacks(szFolder);
if (m_pGameMods)
{
const char *szMOD=m_pGameMods->GetCurrentMod();
// override paks
if (szMOD && (stricmp(szMOD,"FarCry")!=0))
{
string sPaks=string("Mods/")+string(szMOD)+"/"+szFolder;
if (m_pSystem->GetIPak()->OpenPacks(sPaks.c_str()))
return (true);
}
}
return(bFound);
}
//////////////////////////////////////////////////////////////////////////
bool CXGame::ClosePacks(const char *szFolder)
{
if (m_pGameMods)
{
const char *szMOD=m_pGameMods->GetCurrentMod();
if (strlen(szMOD)>0)
{
string sPaks=string("Mods/")+string(szMOD)+"/"+szFolder;
m_pSystem->GetIPak()->ClosePacks(sPaks.c_str());
}
}
return(m_pSystem->GetIPak()->ClosePacks(szFolder));
}
//////////////////////////////////////////////////////////////////////////
string CXGame::GetLevelsFolder() const
{
string sFolder = "Levels";
/*
if (strlen(m_pGameMods->GetCurrentMod()) > 0)
{
// We are using a MOD or TC
const SGameModDescription *pMod = m_pGameMods->GetModDescription( m_pGameMods->GetCurrentMod() );
if (pMod)
{
sFolder = pMod->sFolder + "/Levels";
}
}
*/
return sFolder;
}
//////////////////////////////////////////////////////////////////////////
const char *CXGame::IsMODLoaded()
{
if (m_pGameMods)
{
const char *szMod=m_pGameMods->GetCurrentMod();
if ((szMod) && (stricmp(szMod,"FarCry")!=0))
return (szMod);
}
return (NULL);
}

69
CryGame/GameMods.h Normal file
View File

@@ -0,0 +1,69 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001-2004.
// -------------------------------------------------------------------------
// File name: GameMods.h
// Version: v1.00
// Created: 13/1/2004 by Timur.
// Compilers: Visual Studio.NET 2003
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __GameMods_h__
#define __GameMods_h__
#include "IGame.h"
class CXGame;
//////////////////////////////////////////////////////////////////////////
typedef std::vector<SGameModDescription*> lstMods;
typedef lstMods::iterator lstModsIt;
/*! Implement IGameMods interface to access and manipulate Game Mods.
*/
//////////////////////////////////////////////////////////////////////////
class CGameMods : public IGameMods
{
public:
CGameMods( CXGame *pGame );
~CGameMods();
// IGameMods implementation.
virtual const SGameModDescription* GetModDescription( const char *sModName ) const;
virtual const char* GetCurrentMod() const;
virtual bool SetCurrentMod( const char *sModName,bool bNeedsRestart=false );
virtual const char* GetModPath(const char *szSource);
//! Array of mod descriptions.
lstMods m_mods;
private:
//! Go thru Mods directory and find out what mods are installed.
SGameModDescription* Find( const char *sModName ) const;
void ScanMods();
void ClearMods();
void CloseMod(SGameModDescription *pMod);
bool ParseModDescription(const char *szFolder,SGameModDescription*pMod);
bool GetValue(const char *szKey,const char *szText,char *szRes);
CXGame* m_pGame;
ISystem *m_pSystem;
ILog *m_pILog;
// Name of the mod currently active.
string m_sCurrentMod;
// Current mod
SGameModDescription *m_pMod;
// Used to return the path to other modules
string m_sReturnPath;
};
#endif // __GameMods_h__

332
CryGame/GameMovieUser.cpp Normal file
View File

@@ -0,0 +1,332 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameMovieUser.cpp
//
// History:
// -October 01,2003: Created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include <IMovieSystem.h>
#include "CMovieUser.h"
#include "UISystem.h"
//////////////////////////////////////////////////////////////////////////
void CMovieUser::SetActiveCamera( const SCameraParams &Params )
{
if (!m_pGame)
return;
CXClient *pClient=m_pGame->GetClient();
if (!pClient)
return;
pClient->SetEntityCamera(Params);
}
//////////////////////////////////////////////////////////////////////////
void CMovieUser::ResetCutSceneParams()
{
// Suppress all currently playing sounds.
IConsole *pCon = m_pGame->m_pSystem->GetIConsole();
m_pGame->cl_display_hud->Set(1);
ICVar *pPanoramic=pCon->GetCVar("hud_panoramic");
if(pPanoramic)
pPanoramic->Set(0);
ICVar *pAIUpdate=pCon->GetCVar("ai_systemupdate");
if(pAIUpdate)
pAIUpdate->Set(1);
ICVar *pAIIgnorePlayer=pCon->GetCVar("ai_ignoreplayer");
if(pAIIgnorePlayer)
pAIIgnorePlayer->Set(0);
ICVar *pPhys=pCon->GetCVar("es_UpdatePhysics");
if(pPhys)
pPhys->Set(1);
}
//////////////////////////////////////////////////////////////////////////
void CMovieUser::BeginCutScene(unsigned long dwFlags,bool bResetFx)
{
if (m_InCutSceneCounter > 0)
{
ResetCutSceneParams();
}
m_InCutSceneCounter++;
IConsole *pCon=m_pGame->m_pSystem->GetIConsole();
if(IAnimSequence::IS_16TO9&dwFlags)
{
ICVar *pPanoramic=pCon->GetCVar("hud_panoramic");
if(pPanoramic)
pPanoramic->Set(1);
}
if(IAnimSequence::NO_HUD&dwFlags)
{
m_pGame->cl_display_hud->Set(0);
}
if (IAnimSequence::NO_PLAYER&dwFlags)
{
m_pGame->HideLocalPlayer(true,false);
ICVar *pAIIgnorePlayer=pCon->GetCVar("ai_ignoreplayer");
if(pAIIgnorePlayer)
pAIIgnorePlayer->Set(1);
}
if(IAnimSequence::NO_PHYSICS&dwFlags)
{
ICVar *pPhys=pCon->GetCVar("es_UpdatePhysics");
if(pPhys)
pPhys->Set(0);
}
if(IAnimSequence::NO_AI&dwFlags)
{
ICVar *pAIUpdate=pCon->GetCVar("ai_systemupdate");
if(pAIUpdate)
pAIUpdate->Set(0);
}
IScriptSystem *pSS=m_pGame->GetScriptSystem();
_SmartScriptObject pClientStuff(pSS,true);
if(pSS->GetGlobalValue("ClientStuff",pClientStuff)){
pSS->BeginCall("ClientStuff","OnPauseGame");
pSS->PushFuncParam(pClientStuff);
pSS->EndCall();
}
// do not allow the player to mess around with player's keys
// during a cutscene
GetISystem()->GetIInput()->GetIKeyboard()->ClearKeyState();
m_pGame->m_pIActionMapManager->SetActionMap("player_dead");
m_pGame->AllowQuicksave(false);
// player's weapon might be playing a looping sound ... disable it:
// Resume playing sounds.
if(IAnimSequence::NO_GAMESOUNDS & dwFlags)
{
// lower all other sounds volume when playing cutscene
GetISystem()->GetISoundSystem()->SetGroupScale(SOUNDSCALE_MISSIONHINT,0.5f);
/*
ICVar *pSFXVolume=GetISystem()->GetIConsole()->GetCVar("s_SFXVolume");
if (pSFXVolume)
{
GetISystem()->GetISoundSystem()->SetGroupScale(SOUNDSCALE_MISSIONHINT,0.5f);
}
ICVar *pMusicVolume=GetISystem()->GetIConsole()->GetCVar("s_MusicVolume");
if (pMusicVolume)
{
m_fPrevMusicVolume=pMusicVolume->GetFVal();
pMusicVolume->Set(m_fPrevMusicVolume*0.5f);
}
*/
m_bSoundsPaused = true;
}
if (bResetFx)
{
m_pGame->m_p3DEngine->ResetScreenFx();
/*
ICVar *pResetScreenEffects=pCon->GetCVar("r_ResetScreenFx");
if(pResetScreenEffects)
{
pResetScreenEffects->Set(1);
}
*/
}
}
//////////////////////////////////////////////////////////////////////////
void CMovieUser::EndCutScene()
{
m_InCutSceneCounter--;
if (m_InCutSceneCounter > 0)
return;
m_InCutSceneCounter = 0;
ResetCutSceneParams();
m_pGame->HideLocalPlayer(false,false);
m_pGame->AllowQuicksave(true);
/*
IConsole *pCon=m_pGame->m_pSystem->GetIConsole();
ICVar *pResetScreenEffects=pCon->GetCVar("r_ResetScreenFx");
if(pResetScreenEffects)
{
pResetScreenEffects->Set(0);
}
*/
if (!m_pGame->IsServer())
{
IScriptSystem *pSS=m_pGame->GetScriptSystem();
_SmartScriptObject pClientStuff(pSS,true);
if(pSS->GetGlobalValue("ClientStuff",pClientStuff)){
pSS->BeginCall("ClientStuff","OnResumeGame");
pSS->PushFuncParam(pClientStuff);
pSS->EndCall();
}
}
if (m_bSoundsPaused)
{
GetISystem()->GetISoundSystem()->SetGroupScale(SOUNDSCALE_MISSIONHINT,1.0f);
/*
ICVar *pSFXVolume=GetISystem()->GetIConsole()->GetCVar("s_SFXVolume");
if (pSFXVolume)
{
GetISystem()->GetISoundSystem()->SetGroupScale(SOUNDSCALE_MISSIONHINT,pSFXVolume->GetFVal());
}
ICVar *pMusicVolume=GetISystem()->GetIConsole()->GetCVar("s_MusicVolume");
if (pMusicVolume)
{
pMusicVolume->Set(m_fPrevMusicVolume);
}
*/
}
m_pGame->m_pIActionMapManager->SetActionMap("default");
GetISystem()->GetIInput()->GetIKeyboard()->ClearKeyState();
// we regenerate stamina fpr the local payer on cutsceen end - supposendly he was idle long enough to get it restored
if (m_pGame->GetMyPlayer())
{
CPlayer *pPlayer;
if (m_pGame->GetMyPlayer()->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void**)&pPlayer))
{
pPlayer->m_stats.stamina = 100;
}
}
// reset subtitles
m_pGame->m_pClient->ResetSubtitles();
}
//////////////////////////////////////////////////////////////////////////
void CMovieUser::SendGlobalEvent(const char *pszEvent)
{
HSCRIPTFUNCTION pEventFunc=NULL;
IScriptSystem *pScriptSystem=m_pGame->GetSystem()->GetIScriptSystem();
if (!pScriptSystem)
return;
_SmartScriptObject pMission(pScriptSystem, true);
if (!pScriptSystem->GetGlobalValue("Mission", *pMission))
return;
if (pMission->GetValue(pszEvent, pEventFunc))
{
pScriptSystem->BeginCall(pEventFunc);
// Pass itself as a sender.
pScriptSystem->PushFuncParam(pMission);
pScriptSystem->EndCall();
}
}
//////////////////////////////////////////////////////////////////////////
void CMovieUser::PlaySubtitles( ISound *pSound )
{
assert(pSound);
bool bAlwaysDisplay=0;
if(m_pGame->g_language)
{
char *pLanguage=m_pGame->g_language->GetString();
if(pLanguage)
{
if(!stricmp(pLanguage, "japanese"))
{
bAlwaysDisplay=1;
}
}
}
// always show subtitles if japanese language set (requested), or subtitles console var on
if(bAlwaysDisplay || (m_pGame->cv_game_subtitles && m_pGame->cv_game_subtitles->GetIVal()))
{
char szLabel[2048];
if (m_pGame->m_StringTableMgr.GetSubtitleLabel(pSound->GetName(),szLabel))
{
// CryLogAlways("PLAYSUBTITLE: Subtitle found: %s",szLabel);
// Wait for on play event for this sound, to prevent sound GetLengthMs function to stall execution.
if (pSound->IsLoaded())
{
// If sound loaded do it directly.
OnSoundEvent( SOUND_EVENT_ON_PLAY,pSound );
}
else
{
// Else wait for sound to call us.
pSound->AddEventListener( this );
}
}
// else
//CryLogAlways("PLAYSUBTITLE: Subtitle NOT found: %s",pSound->GetName());
}
if (!pSound->IsPlaying())
pSound->Play();
}
//////////////////////////////////////////////////////////////////////////
void CMovieUser::OnSoundEvent( ESoundCallbackEvent event,ISound *pSound )
{
switch (event)
{
case SOUND_EVENT_ON_PLAY:
{
char szLabel[2048];
if (m_pGame->m_StringTableMgr.GetSubtitleLabel(pSound->GetName(),szLabel))
{
// CryLogAlways("SOUNDEVENT: Subtitle found: %s",szLabel);
//m_pGame->GetSystem()->GetILog()->
//m_pGame->m_pClient->AddHudMessage(szLabel,(float)(pSound->GetLengthMs())/1000.0f);
m_pGame->m_pClient->AddHudSubtitle(szLabel, (float)(pSound->GetLengthMs())/1000.0f);
}
// else
// CryLogAlways("SOUNDEVENT:Subtitle NOT found: %s",szLabel);
}
break;
}
}
//////////////////////////////////////////////////////////////////////////
void CXGame::PlaySequence(const char *pszName,bool bResetFX)
{
// save current sequence name
//char szName[512];strcpy(szName,pszName);
//m_currCutScene=szName; // avoids assigning the Lua string pointer to STL string (unsafe)
m_pSystem->GetIMovieSystem()->PlaySequence(pszName,bResetFX);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::StopCurrentCutscene()
{
// allow to skip only if it has been already played
/*
std::set<string>::iterator it;
it=m_lstPlayedCutScenes.find(m_currCutScene);
if (it!=m_lstPlayedCutScenes.end())
{
*/
m_pSystem->GetIMovieSystem()->StopAllCutScenes();
}

50
CryGame/GameObject.h Normal file
View File

@@ -0,0 +1,50 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _GAMEOBJECT_H_
#define _GAMEOBJECT_H_
struct IScriptObject;
/*!@see IEntityContainer
*/
class CGameObject :
public IEntityContainer
{
public:
//! constructor
CGameObject() {/* m_refCount = 0;*/m_pEntity = NULL; }
//! destructor
virtual ~CGameObject() {}
//! Return entity used by this game object.
IEntity* GetEntity() const { return m_pEntity; }
//! Forwards name calls to entity.
void SetName( const char *s ) { m_pEntity->SetName(s); };
//!@return the name of the entity
const char *GetName() const { return m_pEntity->GetName(); };
// interface IEntityContainer ------------------------------------------------------------
virtual void SetEntity( IEntity *e ) { m_pEntity = e; }
virtual void OnSetAngles( const Vec3 &ang ){};
virtual Vec3 CalcSoundPos() { if (m_pEntity) return m_pEntity->GetPos(); return Vec3(0.0f, 0.0f, 0.0f); }
virtual void Release() { delete this; };
virtual bool QueryContainerInterface(ContainerInterfaceType desired_interface, void** ppInterface) { *ppInterface=0; return false;}
virtual void OnDraw(const SRendParams & RendParams) {}
virtual bool IsSaveable() { return(true); }
virtual void OnEntityNetworkUpdate( const EntityId &idViewerEntity, const Vec3d &v3dViewer, uint32 &inoutPriority,
EntityCloneState &inoutCloneState ) const {}
protected: // ----------------------------------------------------------------------------------------
IEntity * m_pEntity; //!< Entity attached to object.
};
#endif //_GAMEOBJECT_H_

462
CryGame/GameRadar.cpp Normal file
View File

@@ -0,0 +1,462 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameRadar.cpp
//
// History:
// -December 11,2001: created
// -October 31,2003: split from GameLoading.cpp and other files
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
// render game radar
// notes: clean up/optimize code, lots of redundant stuff
//////////////////////////////////////////////////////////////////////////
void CXGame::DrawRadar(float x, float y, float w, float h, float fRange, INT_PTR *pRadarTextures, _SmartScriptObject *pEntities, char *pRadarObjective)
{
// 0 - Radar
// 1 - RadarMask
// 2 - RadarPlayerIcon
// 3 - RadarEnemyInRangeIcon
// 4 - RadarEnemyOutRangeIcon
// 5 - RadarSoundIcon
// 6 - RadarObjectiveIcon
// check if data ok
if (!m_pRenderer || !pRadarTextures || !pRadarObjective)
{
return;
}
IEntity *pPlayer=GetMyPlayer();
if (!pPlayer)
{
return;
}
// clamp minimum value
if(fRange<10.0f)
{
fRange=10.0f;
}
ICVar *pFadeAmount=0;
if(m_pSystem && m_pSystem->GetIConsole())
{
pFadeAmount=m_pSystem->GetIConsole()->GetCVar("hud_fadeamount");
}
float fFadeAmount=1;
if(pFadeAmount)
{
fFadeAmount=pFadeAmount->GetFVal();
}
// set render state
m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
m_pRenderer->Set2DMode(true, 800, 600);
// radar texture id's
INT_PTR iRadarID=pRadarTextures[0],
iRadarMaskID=pRadarTextures[1],
iPlayerIconID=pRadarTextures[2],
iEnemyInRangeIconID=pRadarTextures[3],
iEnemyOutRangeIconID=pRadarTextures[4],
iSoundIconID=pRadarTextures[5],
iObjectiveIconID=pRadarTextures[6];
// last radar alpha/used to mask out sound events
static float fLastAlpha=0.0f, fLastAvgDist=0.0f;
ITimer *pTimer=m_pSystem->GetITimer();
float fCurrPosStep=fLastAlpha*5.0f;
if(fCurrPosStep>1.0f)
{
fCurrPosStep=1.0f;
}
Vec3d fMapCenter(x+w*0.5f, y+h*0.5f, 0.5f);
// render radar/compass
int iPx=0, iPy=0, iW=0, iH=0;
m_pRenderer->GetViewport(&iPx, &iPy, &iW, &iH);
// used to scale y coordinates correctly acoording to aspect ratio
float fScaleY=((float)iW/(float)iH)*0.75f;
// get radar mask data
float fMaskPosX=fMapCenter.x-0.5f*186.0f;
float fMaskPosY=fMapCenter.y-(0.5f*186.0f)*fScaleY;
float fMaskW=186.0f;
float fMaskH=186.0f*fScaleY;
// clear radar background alpha
m_pRenderer->SetState(GS_BLSRC_ONE | GS_BLDST_ZERO | GS_NODEPTHTEST | GS_COLMASKONLYALPHA);
m_pRenderer->Draw2dImage(fMaskPosX, fMaskPosY, fMaskW, fMaskH, iRadarMaskID, 0, 0.1f, 0.1f, 0, 0, 1, 1, 1, 1);
// get radar data
float fRadarPosX=fMapCenter.x-0.5f*130.0f;
float fRadarPosY=fMapCenter.y-(0.5f*130.0f)*fScaleY;
float fRadarW=130.0f;
float fRadarH=(130.0f)*fScaleY;
// render radar mask into alpha channel
m_pRenderer->Draw2dImage(fRadarPosX, fRadarPosY, fRadarW, fRadarH, iRadarMaskID, 0, 1, 1, 0, 0, 1,1, 1, 1);
// add the radar
m_pRenderer->SetState(GS_BLSRC_ONEMINUSDSTALPHA | GS_BLDST_DSTALPHA | GS_NODEPTHTEST);
static float fCurrCompassAngle=pPlayer->GetAngles().z;
float fCurrAngle=pPlayer->GetAngles().z;
fCurrCompassAngle+=(pPlayer->GetAngles().z-fCurrCompassAngle)*pTimer->GetFrameTime()*8.0f;
m_pRenderer->Draw2dImage(fRadarPosX, fRadarPosY, fRadarW, fRadarH, iRadarID, 0, 1, 1, 0, fCurrCompassAngle+90.0f, fFadeAmount,fFadeAmount, fFadeAmount, 1);
// add radar noise..
static float fNoiseMove=0.0f;
fNoiseMove+=pTimer->GetFrameTime()*2.0f;
m_pRenderer->Draw2dImage(fRadarPosX, fRadarPosY, fRadarW, fRadarH, iRadarMaskID, 0+fNoiseMove, 0, 0.1f+fNoiseMove, 1.5f, 0, 1, 1.0f, 1.0f, 1.0f);
// render player icon
float fPlayerSize=16.0f;
float fTexOffset=0.5f/fPlayerSize;
m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
float fPlayerAlpha=(fLastAlpha<=0.6f)? 0.6f: fLastAlpha;
m_pRenderer->Draw2dImage(fMapCenter.x-fPlayerSize*0.5f, fMapCenter.y-fPlayerSize*0.5f,
fPlayerSize, fPlayerSize, iPlayerIconID, fTexOffset, 1-fTexOffset, 1-fTexOffset, fTexOffset, 0, fPlayerAlpha*fFadeAmount, fPlayerAlpha*fFadeAmount, fPlayerAlpha*fFadeAmount, fPlayerAlpha);
// get player position
Vec3d pPlayerPos=pPlayer->GetPos();
// draw sound-events
CXClient *pClient=GetClient();
m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
if (pClient) //&& fLastAlpha>0.0f)
{
TSoundList SoundList=pClient->GetSoundEventList();
float fScale=(w*0.5f); ///fRange;
Matrix33 mtxTransformNoMove;
mtxTransformNoMove.SetScale(Vec3(fScale , (fScale)*fScaleY, 0.0f));
mtxTransformNoMove=mtxTransformNoMove*Matrix33::CreateRotationZ(DEG2RAD(-pPlayer->GetAngles().z));
Matrix34 mtxTransform=mtxTransformNoMove;
Matrix34 TransferVector;
TransferVector.SetTranslationMat(-pPlayer->GetPos());
mtxTransform=mtxTransform*TransferVector;
for (TSoundListIt It=SoundList.begin();It!=SoundList.end();++It)
{
SSoundInfo &SoundInfo=(*It);
if (SoundInfo.fThread==0.0f)
{
// only display threatening sounds
continue;
}
Vec3d pPos=mtxTransform*SoundInfo.Pos;
Vec3d pSoundPos=SoundInfo.Pos;
float fCurrDist=cry_sqrtf((pPlayerPos.x-pSoundPos.x)*(pPlayerPos.x-pSoundPos.x)+(pPlayerPos.y-pSoundPos.y)*(pPlayerPos.y-pSoundPos.y)+(pPlayerPos.z-pSoundPos.z)*(pPlayerPos.z-pSoundPos.z));
float fRadius=fScale*SoundInfo.fRadius/fRange;
float fPhase=SoundInfo.fTimeout/pClient->cl_sound_event_timeout->GetFVal();
pPos.x=-pPos.x;
float fSoundIconSize;
if(fCurrDist>fRange)
{
if(fCurrDist==0.0f)
{
fCurrDist=1.0f;
}
fSoundIconSize=20.0f*(1.0f-fPhase);
fCurrDist=1.0f/fCurrDist;
m_pRenderer->Draw2dImage(fMapCenter.x+pPos.x*fCurrDist-fSoundIconSize*0.5f, fMapCenter.y+pPos.y*fCurrDist-fSoundIconSize*0.5f,
fSoundIconSize, fSoundIconSize, iSoundIconID, 0, 0, 1, 1, 0, fFadeAmount, fFadeAmount, fFadeAmount, fPhase);
}
else
{
fCurrDist/=15.0f;
if(fCurrDist<1.2f && fCurrDist>0.0f)
{
fCurrDist=1.2f;
}
else
if(fCurrDist==0.0f)
{
fCurrDist=1.0f;
}
fSoundIconSize=fRadius*(1.0f-fPhase);
fCurrDist=1.0f/fCurrDist;
m_pRenderer->Draw2dImage(fMapCenter.x+(pPos.x/fRange)-fSoundIconSize*0.5f*fCurrDist, fMapCenter.y+(pPos.y/fRange)-fSoundIconSize*0.5f*fCurrDist, fSoundIconSize*fCurrDist, fSoundIconSize*fCurrDist, iSoundIconID, 0, 0, 1, 1, 0, fFadeAmount, fFadeAmount, fFadeAmount, fPhase);
}
}
}
// draw players
float PlayerZAngle=pPlayer->GetAngles().z;
int nCount=1;
_SmartScriptObject pEntitySO(m_pScriptSystem, true);
_SmartScriptObject pColor(m_pScriptSystem, true);
(*pEntities)->BeginIteration();
// compute average distance to player, for dinamyc radar scale adjustment
float fAvgDist=0.0f;
int iTotalEntities=1;
float fScale=(w*0.5f);
ASSERT(fScale>0.0f);
Matrix33 mtxTransformNoMove;
mtxTransformNoMove.SetScale(Vec3(fScale, (fScale)*fScaleY, 0.0f));
mtxTransformNoMove=mtxTransformNoMove*Matrix33::CreateRotationZ(DEG2RAD(-pPlayer->GetAngles().z));
Matrix34 mtxTransform=mtxTransformNoMove;
Matrix34 TransferVector;
TransferVector.SetTranslationMat(-pPlayer->GetPos());
mtxTransform=mtxTransform*TransferVector;
m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
// show radar objective direction
// get radar objective position
Vec3d pObjectivePos(0,0,0);
int iHaveObjective= strcmp("NoObjective", pRadarObjective);
if(iHaveObjective)
{
if(sscanf(pRadarObjective, "%f %f %f", &pObjectivePos.x, &pObjectivePos.y, &pObjectivePos.z)!=3)
{
return;
}
Vec3d pObjectiveScreenPos=mtxTransform*pObjectivePos;
pObjectiveScreenPos.x=-pObjectiveScreenPos.x;// invert x due to different mapping
// compute distance and sum values
float fCurrDist=cry_sqrtf((pPlayerPos.x-pObjectivePos.x)*(pPlayerPos.x-pObjectivePos.x)+(pPlayerPos.y-pObjectivePos.y)*(pPlayerPos.y-pObjectivePos.y));
float r=0.0f, g=1.0f, b=1.0f, a=1.0f;
if(fCurrDist>fRange)
{
float fPosX=pObjectiveScreenPos.x, fPosY=pObjectiveScreenPos.y;
float fLen=cry_sqrtf(fPosX*fPosX + fPosY*fPosY);
if(fLen)
{
fPosX/=fLen;
fPosY/=fLen;
}
float fOutRangeAngle=0;
if(fPosX<0.0f)
{
fOutRangeAngle=RAD2DEG(cry_acosf(fPosY));
}
else
{
fOutRangeAngle=360.0f-RAD2DEG(cry_acosf(fPosY));
}
m_pRenderer->Draw2dImage(fMapCenter.x+fPosX*52.0f-10.0f*0.5f, fMapCenter.y+fPosY*52.0f*fScaleY-10.0f*0.5f,
10.0f, 10.0f, iEnemyOutRangeIconID, 0, 0, 1, 1, fOutRangeAngle, r*fFadeAmount, g*fFadeAmount, b*fFadeAmount, a*0.5f);
}
else
{
float r=0.0f, g=1.0f, b=1.0f, a=1.0f;
fCurrDist/=15.0f;
if(fCurrDist<1.2f && fCurrDist>0.0f)
{
fCurrDist=1.2f;
}
else
if(fCurrDist==0.0f)
{
fCurrDist=1.0f;
}
fCurrDist=1.0f/fCurrDist;
float fVerticalDist=fabsf(pPlayerPos.z-pObjectivePos.z);
// to distant on vertical range, must be on diferent floor/level, put icons gray
if(fVerticalDist>fRange*0.15f)
{
r*=0.5f;
g*=0.5f;
b*=0.5f;
}
static float fCurrSize=0.0f;
fCurrSize+=pTimer->GetFrameTime()*2.0f;
if(fCurrSize>1.0f)
{
fCurrSize=0.0f;
}
m_pRenderer->Draw2dImage(fMapCenter.x+(pObjectiveScreenPos.x/fRange)-10.0f*fCurrSize*0.5f, fMapCenter.y+(pObjectiveScreenPos.y/fRange)-10.0f*fCurrSize*0.5f,
10.0f*fCurrSize, 10.0f*fCurrSize, iObjectiveIconID, 0, 0, 1, 1, 0.0f, r*a*fFadeAmount, g*a*fFadeAmount, b*a*fFadeAmount, a);
}
}
// render entities
while ((*pEntities)->MoveNext())
{
if (!(*pEntities)->GetCurrent(*pEntitySO))
{
continue;
}
int nId;
if (!pEntitySO->GetValue("nId", nId))
{
continue;
}
IEntity *pEntity=m_pEntitySystem->GetEntity(nId);
if (!pEntity)
{
continue;
}
Vec3d Pos=mtxTransform*pEntity->GetPos();
Pos.x=-Pos.x;// invert x due to different mapping
float r=1.0f, g=1.0f, b=1.0f, a=1.0f;
if (pEntitySO->GetValue("Color", *pColor))
{
pColor->GetValue("r", r);
pColor->GetValue("g", g);
pColor->GetValue("b", b);
pColor->GetValue("a", a);
}
fLastAlpha=a;
// no need to do more stuff..
if(fLastAlpha==0.0f)
{
continue;
}
Matrix33 IconMatrix;
float fAngleZ=PlayerZAngle-pEntity->GetAngles(true).z;
// [marco] temporay fix to be able
// to run a version with debug info
// on and do not get an assert every frame
if (fAngleZ<-360.0f)
{
fAngleZ+=360;
}
else
if (fAngleZ>360.0f)
{
fAngleZ-=360;
}
float fEnemyInRangeSize=10.0f,
fEnemyOutRangeSize=5.0f;
// compute distance and sum values
Vec3d pEntityPos=pEntity->GetPos();
float fCurrDist=cry_sqrtf((pPlayerPos.x-pEntityPos.x)*(pPlayerPos.x-pEntityPos.x)+(pPlayerPos.y-pEntityPos.y)*(pPlayerPos.y-pEntityPos.y));
// skip player..
if(fCurrDist<0.01)
{
continue;
}
// render enemy icons
if(fCurrDist>fRange)
{
if(fCurrDist==0.0f)
{
fCurrDist=1.0f;
}
fCurrDist=1.0f/fCurrDist;
float fPosX=Pos.x, fPosY=Pos.y;
float fLen=cry_sqrtf(fPosX*fPosX + fPosY*fPosY);
if(fLen)
{
fPosX/=fLen;
fPosY/=fLen;
}
float fOutRangeAngle=0;
if(fPosX<0.0f)
{
fOutRangeAngle=RAD2DEG(cry_acosf(fPosY));
}
else
{
fOutRangeAngle=360.0f-RAD2DEG(cry_acosf(fPosY));
}
m_pRenderer->Draw2dImage(fMapCenter.x+Pos.x*fCurrDist*0.98f-fEnemyOutRangeSize*0.5f, fMapCenter.y+Pos.y*fCurrDist*0.98f-fEnemyOutRangeSize*0.5f,
fEnemyOutRangeSize, fEnemyOutRangeSize, iEnemyOutRangeIconID, 0, 0, 1, 1, fOutRangeAngle, 0, a*fFadeAmount, 0, a);
}
else
{
fCurrDist/=15.0f;
if(fCurrDist<1.2f && fCurrDist>0.0f)
{
fCurrDist=1.2f;
}
else
if(fCurrDist==0.0f)
{
fCurrDist=1.0f;
}
fCurrDist=1.0f/fCurrDist;
float fVerticalDist=fabsf(pPlayerPos.z-pEntityPos.z);
// to distant on vertical range, must be on diferent floor/level, put icons gray
if(fVerticalDist>fRange*0.15f)
{
r*=0.5f;
g*=0.5f;
b*=0.5f;
}
m_pRenderer->Draw2dImage(fMapCenter.x+(Pos.x*0.98f/fRange)-fEnemyInRangeSize*0.5f*fCurrDist, fMapCenter.y+(Pos.y*0.98f/fRange)-fEnemyInRangeSize*0.5f*fCurrDist,
fEnemyInRangeSize*fCurrDist, fEnemyInRangeSize*fCurrDist, iEnemyInRangeIconID, 0, 0, 1, 1, fAngleZ+180.0f, r*a*fFadeAmount, g*a*fFadeAmount, b*a*fFadeAmount, a);
}
}
(*pEntities)->EndIteration();
// reset states
m_pRenderer->SetState(GS_NODEPTHTEST);
m_pRenderer->Set2DMode(false, 800, 600);
}

194
CryGame/GameShared.h Normal file
View File

@@ -0,0 +1,194 @@
//////////////////////////////////////////////////////////////////////
//
// Game Source Code
//
// File: GameShared.h
// Description: Stuffs shared by the game's source files.
//
// History:
// - August 9, 2001: Created by Alberto Demichelis
//
//////////////////////////////////////////////////////////////////////
#ifndef GAME_GAMESHARED_H
#define GAME_GAMESHARED_H
#if _MSC_VER > 1000
# pragma once
#endif
//////////////////////////////////////////////////////////////////////////////////////////////
#define INVALID_WID 0 // Invalid WORD ID --- value for the CIDGenerator class
//////////////////////////////////////////////////////////////////////////////////////////////
// Actions
typedef unsigned char ACTIONTYPE;
#define ACTION_MOVE_LEFT 1
//#define ACTIONFLAG_MOVE_LEFT (1<<ACTION_MOVE_LEFT)
#define ACTION_MOVE_RIGHT 2
//#define ACTIONFLAG_MOVE_RIGHT (1<<ACTION_MOVE_RIGHT)
#define ACTION_MOVE_FORWARD 3
//#define ACTIONFLAG_MOVE_FORWARD (1<<ACTION_MOVE_FORWARD)
#define ACTION_MOVE_BACKWARD 4
//#define ACTIONFLAG_MOVE_BACKWARD (1<<ACTION_MOVE_BACKWARD)
#define ACTION_JUMP 5
//#define ACTIONFLAG_JUMP (1<<ACTION_JUMP)
#define ACTION_MOVEMODE 6
//#define ACTIONFLAG_MOVEMODE (1<<ACTION_MOVEMODE)
#define ACTION_FIRE0 7
//#define ACTIONFLAG_FIRE0 (1<<ACTION_FIRE0)
#define ACTION_VEHICLE_BOOST 8 // orphaned
//#define ACTIONFLAG_VEHICLE_BOOST (1<<ACTION_VEHICLE_BOOST)
//<<FIXME>> we need more bits!!
#define ACTION_SCORE_BOARD 8
//#define ACTIONFLAG_SCORE_BOARD (1<<ACTION_SCORE_BOARD)
#define ACTION_RELOAD 9
//#define ACTIONFLAG_RELOAD (1<<ACTION_RELOAD)
#define ACTION_USE 10
//#define ACTIONFLAG_USE (1<<ACTION_USE)
#define ACTION_TURNLR 11
//#define ACTIONFLAG_TURNLR (1<<ACTION_TURNLR)
#define ACTION_TURNUD 12
//#define ACTIONFLAG_TURNUD (1<<ACTION_TURNUD)
#define ACTION_WALK 13
//#define ACTIONFLAG_WALK (1<<ACTION_WALK)
#define ACTION_NEXT_WEAPON 14
//#define ACTIONFLAG_NEXT_WEAPON (1<<ACTION_NEXT_WEAPON)
#define ACTION_PREV_WEAPON 15
//#define ACTIONFLAG_PREV_WEAPON (1<<ACTION_PREV_WEAPON)
#define ACTION_LEANRIGHT 16
//#define ACTIONFLAG_LEANRIGHT (1<<ACTION_LEANRIGHT)
#define ACTION_HOLDBREATH 17
//#define ACTIONFLAG_HOLDBREATH (1<<ACTION_HOLDBREATH)
#define ACTION_FIREMODE 18
//#define ACTIONFLAG_FIREMODE (1<<ACTION_FIREMODE)
#define ACTION_LEANLEFT 19
//#define ACTIONFLAG_LEANLEFT (1<<ACTION_LEANLEFT)
#define ACTION_FIRE_GRENADE 20
//#define ACTIONFLAG_FIRE_GRENADE (1<<ACTION_FIRE_GRENADE)
#define ACTION_WEAPON_0 21
#define ACTION_WEAPON_1 (ACTION_WEAPON_0+1)
#define ACTION_WEAPON_2 (ACTION_WEAPON_0+2)
#define ACTION_WEAPON_3 (ACTION_WEAPON_0+3)
#define ACTION_WEAPON_4 (ACTION_WEAPON_0+4)
/*#define ACTION_WEAPON_5 (ACTION_WEAPON_0+5)
#define ACTION_WEAPON_6 (ACTION_WEAPON_0+6)
#define ACTION_WEAPON_7 (ACTION_WEAPON_0+7)
#define ACTION_WEAPON_8 (ACTION_WEAPON_0+8)
*/
#define ACTION_CYCLE_GRENADE (ACTION_WEAPON_0+9)
#define ACTION_DROPWEAPON (ACTION_WEAPON_0+10)
#define ACTION_CONCENTRATION 32
//#define ACTIONFLAG_WEAPON_0 (1<<ACTION_WEAPON_0)
//#define ACTIONFLAG_WEAPON_1 (1<<ACTION_WEAPON_1)
//#define ACTIONFLAG_WEAPON_2 (1<<ACTION_WEAPON_2)
//#define ACTIONFLAG_WEAPON_3 (1<<ACTION_WEAPON_3)
//#define ACTIONFLAG_WEAPON_4 (1<<ACTION_WEAPON_4)
//#define ACTIONFLAG_WEAPON_5 (1<<ACTION_WEAPON_5)
//#define ACTIONFLAG_WEAPON_6 (1<<ACTION_WEAPON_6)
//#define ACTIONFLAG_WEAPON_7 (1<<ACTION_WEAPON_7)
//#define ACTIONFLAG_WEAPON_8 (1<<ACTION_WEAPON_8)
//#define ACTIONFLAG_WEAPON_9 (1<<ACTION_WEAPON_9)
//#define ACTIONFLAG_DROPWEAPON (1<<ACTION_DROPWEAPON)
//client side only
#define ACTION_ITEM_0 35
#define ACTION_ITEM_1 36
#define ACTION_ITEM_2 37
#define ACTION_ITEM_3 38
#define ACTION_ITEM_4 39
#define ACTION_ITEM_5 40
#define ACTION_ITEM_6 41
#define ACTION_ITEM_7 42
#define ACTION_ITEM_8 43
#define ACTION_ZOOM_TOGGLE 45
#define ACTION_ZOOM_IN 46
#define ACTION_ZOOM_OUT 47
//#define ACTION_RELOAD_WEAPON 48
#define ACTION_MOVEMODE2 49
//#define ACTIONLOCALFLAG_MOVEMODE2 1
////#define ACTIONFLAG_RUN (1<<ACTION_RUN)
//#define ACTION_QUICKLOAD 50
//#define ACTION_QUICKSAVE 51
#define ACTION_SAVEPOS 54
#define ACTION_LOADPOS 55
#define ACTION_FIRECANCEL 56
#define ACTION_FLASHLIGHT 57
// to switch between 1st and 3rd person mode while driving
// and shooting
#define ACTION_CHANGE_VIEW 58
//
// make player run very fast
#define ACTION_RUNSPRINT 59
#define ACTION_MESSAGEMODE 60
#define ACTION_MESSAGEMODE2 61
#define ACTION_TAKESCREENSHOT 62
#define ACTION_MOVEMODE_TOGGLE 63
#define ACTION_AIM_TOGGLE 64
//////////////////////////////////////////////////////////////////////////////////////////////
#define PLAYER_MAX_WEAPONS 9
//////////////////////////////////////////////////////////////////////////
typedef struct
{
int m_nFireMode; //< active firemode
std::vector<int> m_nAmmoInClip; //< amount of ammo in the clip of that firemode
} tWeaponPersistentData;
typedef struct
{
bool m_bDataSaved;
int m_nHealth,m_nArmor;
int m_nSelectedWeaponID;
int m_nAmmo; //< only valid if m_nSelectedWeaponID != -1
int m_nAmmoInClip; //< only valid if m_nSelectedWeaponID != -1
int m_vWeaponSlots[PLAYER_MAX_WEAPONS];
std::map<int, tWeaponPersistentData> m_mapWeapons;
std::map<string, int> m_mapAmmo;
std::list<string> m_lItems;
} tPlayerPersistentData;
//////////////////////////////////////////////////////////////////////////
#endif // GAME_GAMESHARED_H

137
CryGame/GameTagPoints.cpp Normal file
View File

@@ -0,0 +1,137 @@
//////////////////////////////////////////////////////////////////////
//
// Game source code (c) Crytek 2001-2003
//
// File: GameTagPoints.cpp
//
// History:
// -December 11,2001: created
// -October 31,2003: split from GameLoading.cpp and other files
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XClient.h"
#include "UIHud.h"
#include "XPlayer.h"
#include "PlayerSystem.h"
#include "XServer.h"
#include "WeaponSystemEx.h"
#include "ScriptObjectGame.h"
#include "ScriptObjectInput.h"
#include <IEntitySystem.h>
#include "UISystem.h"
#include "ScriptObjectUI.h"
#include "TagPoint.h"
//#include "XPath.h"
//////////////////////////////////////////////////////////////////////
// Inserts a tag-point in the list.
ITagPoint *CXGame::CreateTagPoint(const string &name, const Vec3d &pos, const Vec3d &angles)
{
// if a tag point with this name doesn't exist
//if (m_mapTagPoints.find(name) == m_mapTagPoints.end() )
//{
// create new one
CTagPoint *pNewPoint = new CTagPoint(this);
pNewPoint->OverrideName(name.c_str());
pNewPoint->SetPos(pos);
pNewPoint->SetAngles(angles);
// insert it into the map
m_mapTagPoints.insert(TagPointMap::iterator::value_type(name,pNewPoint));
return (ITagPoint *) pNewPoint;
//}
//else
// return 0;
}
//////////////////////////////////////////////////////////////////////
// Remove tag-point.
void CXGame::RemoveTagPoint(ITagPoint *pPoint)
{
TagPointMap::iterator ti;
// find and delete tag-point
for (ti = m_mapTagPoints.begin();ti!=m_mapTagPoints.end();ti++)
{
if ( ti->second == pPoint )
{
m_mapTagPoints.erase(ti);
pPoint->Release();
return;
}
}
}
//////////////////////////////////////////////////////////////////////
// Retrieve a tag-point by its name
ITagPoint *CXGame::GetTagPoint(const string &name)
{
TagPointMap::iterator ti;
// find and return tag-point
if ((ti = m_mapTagPoints.find(name)) == m_mapTagPoints.end())
return 0;
else
return (ITagPoint *) ti->second;
}
//////////////////////////////////////////////////////////////////////
bool CXGame::RenameTagPoint(const string &oldname, const string &newname)
{
TagPointMap::iterator ti;
// find tag-point
if (( ti = m_mapTagPoints.find(oldname)) != m_mapTagPoints.end())
{
// does the new name already exist ?
if (m_mapTagPoints.find(newname) == m_mapTagPoints.end())
{
// change name
CTagPoint *pPoint = ti->second;
pPoint->OverrideName(newname);
m_mapTagPoints.erase(oldname);
m_mapTagPoints.insert(TagPointMap::iterator::value_type(newname,pPoint));
return true;
}
else
return false;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
//! Remove all tag-points from the list
void CXGame::ClearTagPoints()
{
if (!m_mapTagPoints.empty())
{
TagPointMap::iterator ti;
for (ti=m_mapTagPoints.begin();ti!=m_mapTagPoints.end();ti++)
(ti->second)->Release();
m_mapTagPoints.clear();
}
if(m_pServer)m_pServer->ClearRespawnPoints();
}
//////////////////////////////////////////////////////////////////////////
void CXGame::AddRespawnPoint(ITagPoint *pPoint)
{
// m_pServer->m_vRespawnPoints.push_back(pPoint);
m_pServer->AddRespawnPoint(pPoint);
}
//////////////////////////////////////////////////////////////////////////
void CXGame::RemoveRespawnPoint(ITagPoint *pPoint)
{
m_pServer->RemoveRespawnPoint(pPoint);
}

98
CryGame/IXSystem.h Normal file
View File

@@ -0,0 +1,98 @@
//////////////////////////////////////////////////////////////////////
//
// Game Source Code
//
// File: IXSystem.h
// Description: Pure system interface.
//
// History:
// - August 8, 2001: Created by Alberto Demichelis
//
//////////////////////////////////////////////////////////////////////
#ifndef GAME_IXSYSTEM_H
#define GAME_IXSYSTEM_H
#if _MSC_VER > 1000
# pragma once
#endif
#include <EntityDesc.h>
//////////////////////////////////////////////////////////////////////////////////////////////
// Forward declarations
struct IEntity;
struct ICVar;
typedef std::set<int> EntitiesSet;
typedef EntitiesSet::iterator EntitiesSetItor;
#define MAXTEAMS 8
//////////////////////////////////////////////////////////////////////////////////////////////
// IXSystem interface
struct IXSystem
{
//! delete the class
virtual void Release() = 0;
//! load the level [EDITOR ONLY]
virtual bool LoadLevel(const char *szLevelDir,const char *szMissionName = 0,bool bEditor=false) = 0;
//! add in the map and set the ID
virtual IEntity* SpawnEntity(class CEntityDesc &ed) = 0;
//! remove from the map and the entity system of the framework
virtual void RemoveEntity(EntityId wID, bool bRemoveNow=false) = 0;
//! remove and delete all existing entities still registered
virtual void DeleteAllEntities() = 0;
//! called on a disconnection
virtual void Disconnected(const char *szCause) = 0;
//! sets the team of an entity
virtual void SetTeam(EntityId nEntId, int nTeamId) = 0;
//! adds a team(return the new team id)
virtual int AddTeam(const char *sTeam, int nTeamId=-1) = 0;
//! removes a team
virtual void RemoveTeam(int nTeamId) = 0;
//! set team score
virtual void SetTeamScore(int nTeamId,short nScore) = 0;
//! set team flags
virtual void SetTeamFlags(int nTeamId,int nFlags) = 0;
//! get team score
virtual int GetTeamScore(int nTeamId) = 0;
//! get team flags
virtual int GetTeamFlags(int nTeamId) = 0;
//! get team score
virtual int GetEntityTeam(int nEntity) = 0;
//! get team name
virtual bool GetTeamName(int nTeamId,char *ret) = 0;
//! get team id
virtual int GetTeamId(const char *name) = 0;
//! get the number of players in a team
virtual int GetTeamMembersCount(int nTeamiId) = 0;
//! serialize info for the context setup
virtual bool WriteTeams(CStream &stm) = 0;
//! read infos from the context setup
virtual bool ReadTeams(CStream &stm) = 0;
//!bind an entity to another one
virtual void BindEntity(EntityId idParent,EntityId idChild)=0;
//!unbind an entity from another one
virtual void UnbindEntity(EntityId idParent,EntityId idChild)=0;
//! return a pointer to the entity matching with entity ID
virtual IEntity* GetEntity(EntityId wID) = 0;
//! retrun a pointer to the entity matching with a certain name
virtual IEntity* GetEntity(const char *sEntity) = 0;
virtual bool IsLevelEntity(EntityId id) = 0;
//! return the entity assigned as player of le local client if exists, if not return null
virtual IEntity *GetLocalPlayer() = 0;
//! return all entities
virtual IEntityIt *GetEntities() = 0;
//! return all player entities
virtual EntitiesSet& GetPlayerEntities() = 0;
//! return true if the given entity is in the entity list
virtual bool EntityExists(WORD id) = 0;
virtual unsigned short GetLevelDataCheckSum() = 0;
// parses the properties from XML and fills the corresponding table with the values
virtual void SetEntityProperties(IEntity * pEntity,XDOM::IXMLDOMNode * pPropNode) = 0;
virtual void OnSpawn(IEntity *ent, CEntityDesc & ed)=0;
virtual void OnSpawnContainer( CEntityDesc &ed,IEntity *pEntity )=0;
virtual void OnSetVar(ICVar *pVar) = 0;
virtual void SetVariable(const char *sName,const char *sValue) = 0;
virtual void BindChildren()=0;
};
#endif // GAME_IXSYSTEM_H

219
CryGame/IngameDialog.cpp Normal file
View File

@@ -0,0 +1,219 @@
// IngameDialog.cpp: implementation of the CIngameDialog class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "IngameDialog.h"
#define EDGESIZE 8.0f
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CIngameDialog::CIngameDialog()
{
m_fX=0.0f;
m_fY=0.0f;
m_fW=0.0f;
m_fH=0.0f;
m_sText="";
m_pRenderer=NULL;
m_pFont=NULL;
m_nFillId=0;
m_bInited=false;
}
//////////////////////////////////////////////////////////////////////////
CIngameDialog::~CIngameDialog()
{
}
//////////////////////////////////////////////////////////////////////////
// INit the dialog; must be called before all other function of this class.
bool CIngameDialog::Init(CIngameDialogMgr *pMgr, int nId, ISystem *pSystem, int nFillId, const char *pszFontName, const char *pszEffectName, int nSize, string sText,wstring swText, float fTimeout)
{
if (m_bInited || (!pSystem) || (sText.empty() && swText.empty()))
return (false);
m_pRenderer=pSystem->GetIRenderer();
if (!m_pRenderer)
return (false);
if ((!m_pRenderer->GetWidth()) || (!m_pRenderer->GetHeight()))
return false;
m_sEffect=pszEffectName;
ICryFont *pCryFont = pSystem->GetICryFont();
if(!pCryFont) // is 0 on the dedicated server
return false;
m_pFont=pCryFont->GetFont(pszFontName);
if (m_pFont)
m_pFont->SetEffect(m_sEffect.c_str());
else
{
m_pFont=pSystem->GetICryFont()->GetFont("Default");
m_pFont->SetEffect("IngameDlg");
}
m_nSize=nSize;
vector2f hsize ((float)m_nSize, (float)m_nSize);
m_pFont->SetSize(hsize);
// calculate size of box
m_pFont->SetSameSize(false);
m_pFont->SetCharWidthScale(1.0f);
bool b=m_pFont->GetSameSize();
float f=m_pFont->GetCharWidthScale();
vector2f Size;
if (!sText.empty())
Size=m_pFont->GetTextSize(sText.c_str());
else
Size=m_pFont->GetTextSizeW(swText.c_str());
m_fW=Size.x*(800.0f/m_pRenderer->GetWidth());
m_fH=Size.y*(600.0f/m_pRenderer->GetHeight());
m_pMgr=pMgr;
m_nId=nId;
m_nFillId=nFillId;
m_sText=sText;
m_swText=swText;
m_fTimeout=fTimeout;
m_bInited=true;
return true;
}
//////////////////////////////////////////////////////////////////////////
void CIngameDialog::SetPos(float x, float y)
{
m_fX=x;
m_fY=y;
}
//////////////////////////////////////////////////////////////////////////
bool CIngameDialog::Update()
{
if (!m_bInited)
return false;
vector2f hsize ((float)m_nSize, (float)m_nSize);
m_pFont->SetSize(hsize);
m_pFont->SetEffect(m_sEffect.c_str());
m_pFont->SetSameSize(false);
m_pFont->SetCharWidthScale(1.0f);
// draw fill
m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
// disabled, it was rendering strange black rectangle at beggining of missions
//m_pRenderer->Draw2dImage(m_fX, m_fY, EDGESIZE+EDGESIZE+m_fW, EDGESIZE+EDGESIZE+m_fH, m_nFillId, 0, 1, 1, 0, 0, 1.0f, 1.0f, 1.0f, 1.0f);
m_pRenderer->SetState(GS_NODEPTHTEST);
// draw text
color4f hcolor(1.0f, 1.0f, 1.0f, 1.0f);
m_pFont->SetColor(hcolor, -1);
m_pFont->DrawString(m_fX+EDGESIZE,m_fY+EDGESIZE, m_sText.c_str());
return true;
}
//////////////////////////////////////////////////////////////////////////
CIngameDialogMgr::CIngameDialogMgr()
{
m_nNextId=0;
m_nDefaultFillId=-1;
m_pRenderer=NULL;
m_pTimer=NULL;
}
//////////////////////////////////////////////////////////////////////////
CIngameDialogMgr::~CIngameDialogMgr()
{
// delete all dialogs
std::list<SIGDId*>::iterator lstDialogsIt;
lstDialogsIt=m_lstDialogs.begin();
while (lstDialogsIt!=m_lstDialogs.end())
{
delete ((*lstDialogsIt)->pDialog);
delete (*lstDialogsIt);
lstDialogsIt=m_lstDialogs.erase(lstDialogsIt);
}
// remove default fill-texture
if (m_pRenderer && (m_nDefaultFillId>=0))
m_pRenderer->RemoveTexture(m_nDefaultFillId);
}
//////////////////////////////////////////////////////////////////////////
// Adds a new dialog on the screen.
int CIngameDialogMgr::AddDialog(ISystem *pSystem, int nFillId, const char *pszFontName, const char *pszEffectName, int nSize, string sText,wstring swText, float fTimeout)
{
if (!m_pRenderer)
m_pRenderer=pSystem->GetIRenderer();
if (!m_pTimer)
m_pTimer=pSystem->GetITimer();
string sFontName="default";
string sEffectName="IngameDlg";
// load default fill-texture if not loaded yet
if (m_pRenderer && (m_nDefaultFillId<0))
{
m_nDefaultFillId=m_pRenderer->LoadTexture("textures/gui/igdlg_fill");
}
if (pszFontName && strlen(pszFontName))
sFontName=pszFontName;
if (pszEffectName && strlen(pszEffectName))
sEffectName=pszEffectName;
if (nFillId<0)
nFillId=m_nDefaultFillId;
// create dialog and put in list
SIGDId *pIGDId=new SIGDId();
pIGDId->pDialog=new CIngameDialog();
pIGDId->nId=m_nNextId++;
pIGDId->pDialog->Init(this, pIGDId->nId, pSystem, nFillId, sFontName.c_str(), sEffectName.c_str(), nSize, sText,swText, fTimeout);
m_lstDialogs.push_back(pIGDId);
return pIGDId->nId;
}
//////////////////////////////////////////////////////////////////////////
// Removes a dialog from the screen and destroys it.
void CIngameDialogMgr::RemoveDialog(int nId)
{
// find and remove dialog
std::list<SIGDId*>::iterator lstDialogsIt;
lstDialogsIt=m_lstDialogs.begin();
while (lstDialogsIt!=m_lstDialogs.end())
{
SIGDId *pIGDId=(*lstDialogsIt);
if (pIGDId->nId==nId)
{
delete (pIGDId->pDialog);
delete pIGDId;
m_lstDialogs.erase(lstDialogsIt);
return;
}
lstDialogsIt++;
}
}
//////////////////////////////////////////////////////////////////////////
// Updates and draws all dialogs on the screen. Should be called every frame.
void CIngameDialogMgr::Update()
{
float y=55.0f;
std::list<SIGDId*>::iterator lstDialogsIt;
lstDialogsIt=m_lstDialogs.begin();
while (lstDialogsIt!=m_lstDialogs.end())
{
SIGDId *pIGDId=(*lstDialogsIt);
if (pIGDId->pDialog->m_fTimeout)
{
pIGDId->pDialog->m_fTimeout-=m_pTimer->GetFrameTime();
if (pIGDId->pDialog->m_fTimeout<=0.0f)
{
delete (pIGDId->pDialog);
delete pIGDId;
lstDialogsIt=m_lstDialogs.erase(lstDialogsIt);
continue;
}
}
pIGDId->pDialog->SetPos(10.0f, y);
pIGDId->pDialog->Update();
y+=pIGDId->pDialog->GetHeight()+EDGESIZE+EDGESIZE+5.0f;
lstDialogsIt++;
}
}

77
CryGame/IngameDialog.h Normal file
View File

@@ -0,0 +1,77 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// IngameDialog.h: interface for the CIngameDialog class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_INGAMEDIALOG_H__F50111D1_2478_41B5_8AC5_5DD6A104BDEA__INCLUDED_)
#define AFX_INGAMEDIALOG_H__F50111D1_2478_41B5_8AC5_5DD6A104BDEA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>
struct ISystem;
struct IFFont;
class CIngameDialogMgr;
class CIngameDialog
{
private:
CIngameDialog();
virtual ~CIngameDialog();
bool Init(CIngameDialogMgr *pMgr, int nId, ISystem *pSystem, int nFillId, const char *pszFontName, const char *pszEffectName, int nSize, string sText,wstring swText, float fTimeout);
void SetPos(float x, float y);
float GetHeight() { return m_fH; }
bool Update();
friend class CIngameDialogMgr;
private:
CIngameDialogMgr *m_pMgr;
int m_nId;
float m_fX;
float m_fY;
float m_fW;
float m_fH;
int m_nSize;
string m_sText;
wstring m_swText;
IRenderer *m_pRenderer;
IFFont *m_pFont;
string m_sEffect;
int m_nFillId;
float m_fTimeout;
bool m_bInited;
};
// You must use this manager !
struct SIGDId
{
int nId;
CIngameDialog *pDialog;
};
class CIngameDialogMgr
{
private:
int m_nDefaultFillId;
int m_nNextId;
IRenderer *m_pRenderer;
ITimer *m_pTimer;
std::list<SIGDId*> m_lstDialogs;
public:
CIngameDialogMgr();
~CIngameDialogMgr();
int AddDialog(ISystem *pSystem, int nFillId, const char *pszFontName, const char *pszEffectName, int nSize, string sText, wstring swText, float fTimeout=0.0f); // return id to dialog
void RemoveDialog(int nId);
void Update();
};
#endif // !defined(AFX_INGAMEDIALOG_H__F50111D1_2478_41B5_8AC5_5DD6A104BDEA__INCLUDED_)

5
CryGame/MSSCCPRJ.SCC Normal file
View File

@@ -0,0 +1,5 @@
SCC = This is a source code control file
[CryGame.vcproj]
SCC_Aux_Path = "P4SCC#perforce:1666##marcoc_code##PC018"
SCC_Project_Name = Perforce Project

286
CryGame/NetEntityInfo.cpp Normal file
View File

@@ -0,0 +1,286 @@
// NetEntityInfo.cpp: implementation of the CNetEntityInfo class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "NetEntityInfo.h"
#include "XPlayer.h"
#include "XVehicle.h"
#include "XSystemBase.h"
#include <ITimer.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CNetEntityInfo::CNetEntityInfo()
{
m_pEntity=0;
m_fLastUpdate=0;
m_pTimer=NULL;
m_nScore=0;
m_cState=0;
m_dwBitSizeEstimate=40; // inital guessed value
}
//////////////////////////////////////////////////////////////////////////
CNetEntityInfo::CNetEntityInfo(const CNetEntityInfo& nei)
{
m_pEntity=nei.m_pEntity;
m_fLastUpdate=nei.m_fLastUpdate;
m_pTimer=nei.m_pTimer;
m_nPriority=nei.m_nPriority;
m_nScore=nei.m_nScore;
m_cState=nei.m_cState;
m_ecsClone=nei.m_ecsClone;
m_dwBitSizeEstimate=nei.m_dwBitSizeEstimate;
}
//////////////////////////////////////////////////////////////////////////
CNetEntityInfo::CNetEntityInfo(CXServerSlot *pServerSlot,ITimer *pTimer,IEntity* pEntity)
{
m_pEntity=pEntity;
m_fLastUpdate=0;
m_pTimer=pTimer;
m_nScore=0;
m_cState=0;
m_ecsClone.m_v3Angles.Set(1E10f,1E10f,1E10f);
m_ecsClone.m_pServerSlot=pServerSlot;
m_dwBitSizeEstimate=40; // inital guessed value
}
//////////////////////////////////////////////////////////////////////////
CNetEntityInfo::~CNetEntityInfo()
{
}
//////////////////////////////////////////////////////////////////////////
bool CNetEntityInfo::Write( CXServer *pServer, CStream &stm)
{
assert(pServer);
bool bRes;
m_ecsClone.m_fWriteStepBack = GetXServerSlot()->GetPlayerWriteStepBack();
m_ecsClone.m_bOffSync = GetXServerSlot()->IsEntityOffSync(m_pEntity->GetId());
size_t dwPos = stm.GetSize();
bRes=m_pEntity->Write(stm,&m_ecsClone);
m_dwBitSizeEstimate = 5+9 + (uint32)(stm.GetSize()-dwPos); // 5 for XSERVERMSG_UPDATEENTITY, 9 for EntityId
return bRes;
}
//////////////////////////////////////////////////////////////////////////
void CNetEntityInfo::Reset()
{
m_fLastUpdate=m_pTimer->GetCurrTime();
CXServer *pServer = GetXServerSlot()->GetServer();
if(pServer->m_pGame->GetMyPlayer())
if((pServer->sv_netstats->GetIVal() > 1) &&
(pServer->GetServerSlotByEntityId(pServer->m_pGame->GetMyPlayer()->GetId()) == GetXServerSlot()))
{
int i;
if(GetISystem()->GetIEntitySystem()->IsDynamicEntityId(m_pEntity->GetId()))
i=(int)(0xffff-m_pEntity->GetId());
else
i=1000-(int)(m_pEntity->GetId());
if(i>=1000)i=1000-1; // clamp in max range
if(i<0)i=0; // clamp in min range
GetXServerSlot()->GetServer()->m_NetStats.AddToSumGraph(i, 1);
}
}
//////////////////////////////////////////////////////////////////////////
uint32 CNetEntityInfo::CalcEstimatedSize()
{
return m_dwBitSizeEstimate;
}
//////////////////////////////////////////////////////////////////////////
void CNetEntityInfo::Update(Vec3d v3dViewer)
{
FUNCTION_PROFILER( GetISystem(), PROFILE_GAME );
CXServer *pServer = GetXServerSlot()->GetServer();
IBitStream *pBitStream = pServer->m_pGame->GetIBitStream(); // compression helper
m_nPriority=1; // lowest update level
if(!m_pEntity)
{
assert(m_pEntity);
// ::OutputDebugString("Warning invalid CNetEntityInfo!!\n");
// m_bNeedUpdate=false;
m_nPriority=0; // no update at all
return;
}
/////////////////////////////////////////////////
unsigned char cState=(unsigned char)m_pEntity->GetStateIdx();
if(!m_pEntity->IsStateClientside() // state changes need sync
&& m_cState!=cState) // state has changed
{
// send it to the client
CStream stm;
//if there were no previous state - this is the first time state is set
bool bFirstTime = (m_cState==0);
m_cState=cState;
WRITE_COOKIE(stm);
pBitStream->WriteBitStream(stm,(EntityId)m_pEntity->GetId(),eEntityId);
// stm.Write((EntityId)m_pEntity->GetId());
ASSERT(m_pEntity->IsInState(cState));
stm.Write(cState);
WRITE_COOKIE(stm);
GetXServerSlot()->SendReliableMsg(XSERVERMSG_SETENTITYSTATE,stm,false,m_pEntity->GetName());
//we need to know if this is the first time - then make it execute OnBind on client
if(bFirstTime)
m_pEntity->SinkRebind( GetXServerSlot()->GetServer() );
}
if(m_pEntity->IsGarbage())
{
m_nPriority=0; // no update at all
return;
}
/////////////////////////////////////////////////
if(!m_pEntity->GetNetPresence())
{
m_nPriority=0; // no update at all
return;
}
bool bLocalPlayer = GetXServerSlot()->GetPlayerId()==m_pEntity->GetId();
/////////////////////////////////////////////////
if(bLocalPlayer)
m_nPriority+=1000000;
IEntityContainer *pC=m_pEntity->GetContainer();
m_ecsClone.m_bSyncAngles = true;
m_ecsClone.m_bSyncYAngle = true;
m_ecsClone.m_bLocalplayer = bLocalPlayer; // different from earlier method (was only true for a Player, not for spectators)
Vec3d v3This=m_pEntity->GetPos();
// lower priority for more distant entities
{
float fDistance2=0;
if(!IsEquivalent(v3dViewer,v3This))
fDistance2 = (v3dViewer-(const Vec3d)v3This).len2();
float fVisibleRadius2=500*500;
if(fDistance2>fVisibleRadius2)
m_nPriority=100; // almost no udate
else
m_nPriority+=(unsigned int)cry_sqrtf(fVisibleRadius2-fDistance2);
}
// container gets the change to change the m_nPriority
if(pC)
pC->OnEntityNetworkUpdate(GetXServerSlot()->GetPlayerId(),v3dViewer,m_nPriority,m_ecsClone);
if(!m_nPriority)
return; // no update at all
CPlayer *pPlayer=0;
if(pC)
pC->QueryContainerInterface(CIT_IPLAYER,(void **)&pPlayer);
if(pPlayer)
{
//if is the slot's player
if(bLocalPlayer)
{
if(pPlayer->m_stats.score!=m_nScore)
{
CStream stm;
m_nScore=pPlayer->m_stats.score;
WRITE_COOKIE(stm);
stm.Write(m_pEntity->GetId());
stm.Write(m_nScore);
WRITE_COOKIE(stm);
GetXServerSlot()->SendReliableMsg(XSERVERMSG_SETPLAYERSCORE,stm,true);
}
}
}
if(m_nUpdateNumber==0)
{
m_nPriority=0x0000FFFF;
m_nUpdateNumber++;
return;
}
m_nUpdateNumber++;
}
//////////////////////////////////////////////////////////////////////////
float CNetEntityInfo::GetTimeAffectedPriority()
{
float fCurrentTime = m_pTimer->GetCurrTime();
float fDeltaTime=fCurrentTime-m_fLastUpdate;
if(fDeltaTime<0)
{
m_fLastUpdate=fCurrentTime; // timer was reseted
fDeltaTime=0;
}
return (float)m_nPriority*fDeltaTime;
}
//////////////////////////////////////////////////////////////////////////
float CNetEntityInfo::GetDistanceTo( const Vec3d &vPos )
{
assert(m_pEntity);
if(!m_pEntity)
return 0;
Vec3d v3This=m_pEntity->GetPos();
return (vPos-(const Vec3d)v3This).len2();
}
//////////////////////////////////////////////////////////////////////////
bool CNetEntityInfo::operator ==(EntityId id) const
{
if(!m_pEntity)
return false;
if(m_pEntity->GetId()==id)
return true;
return false;
}
//////////////////////////////////////////////////////////////////////////
CXServerSlot *CNetEntityInfo::GetXServerSlot()
{
return m_ecsClone.m_pServerSlot;
}

74
CryGame/NetEntityInfo.h Normal file
View File

@@ -0,0 +1,74 @@
// NetEntityInfo.h: interface for the CNetEntityInfo class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_NETENTITYINFO_H__6641B99B_3343_4117_BA60_92A4BFCC2056__INCLUDED_)
#define AFX_NETENTITYINFO_H__6641B99B_3343_4117_BA60_92A4BFCC2056__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IEntitySystem.h>
struct ITimer;
class CPlayer;
class CNetEntityInfo
{
public:
//! constructor
explicit CNetEntityInfo();
//! constructor
CNetEntityInfo(const CNetEntityInfo& nei);
//! constructor
CNetEntityInfo(CXServerSlot *pServerSlot,ITimer *pTimer,IEntity* pEntity);
//! destructor
virtual ~CNetEntityInfo();
// -------------------------------------------------------------------------------
//! \param pServer must not be 0
bool Write( CXServer *pServer, CStream &stm );
//!
bool NeedUpdate(){ return m_nPriority!=0; }
//!
void Update(Vec3 v3d);
//!
void Reset();
//!
void Invalidate(){m_pEntity=NULL;};
//!
bool operator ==(EntityId id) const;
//!
inline IEntity *GetEntity(){return m_pEntity;}
//!
inline unsigned int GetPriority(){return m_nPriority;}
//!
float GetTimeAffectedPriority();
//!
float GetDistanceTo( const Vec3d &vPos );
//! \return in bits
uint32 CalcEstimatedSize();
private: // --------------------------------------------------------------------------
IEntity * m_pEntity; //!<
float m_fLastUpdate; //!< absolute time
short m_nScore; //!< only used for bLocalPlayer==true, from struct PlayerStats.score
ITimer * m_pTimer; //!<
char m_cState; //!< entity state
uint32 m_dwBitSizeEstimate; //!< based on last packet size (maybe this needs to be improved), in bits per packet
//temp vars for determinate the priority
uint32 m_nPriority; //!< 0=no update at all, 1=lowest update priority ...
uint32 m_nUpdateNumber; //!<
EntityCloneState m_ecsClone; //!<
//! \return pointer is always valid
CXServerSlot *GetXServerSlot();
};
#endif // !defined(AFX_NETENTITYINFO_H__6641B99B_3343_4117_BA60_92A4BFCC2056__INCLUDED_)

34
CryGame/PlayerSystem.h Normal file
View File

@@ -0,0 +1,34 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// PlayerSystem.h: interface for the CPlayerSystem class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_PLAYERSYSTEM_H__9A74BB7C_D0B5_4B01_BCF7_ED9E03F7A25C__INCLUDED_)
#define AFX_PLAYERSYSTEM_H__9A74BB7C_D0B5_4B01_BCF7_ED9E03F7A25C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
typedef std::vector<EntityClassId> PlayerVector;
//!store all player entity class ids
class CPlayerSystem
{
PlayerVector m_vPlayerClasses;
public:
CPlayerSystem(){}
virtual ~CPlayerSystem(){}
void AddPlayerClass(const EntityClassId classid) { m_vPlayerClasses.push_back(classid);}
bool IsPlayerClass(const EntityClassId classid) { return ( m_vPlayerClasses.end() != std::find(m_vPlayerClasses.begin(),m_vPlayerClasses.end(), classid) );}
};
#endif // !defined(AFX_PLAYERSYSTEM_H__9A74BB7C_D0B5_4B01_BCF7_ED9E03F7A25C__INCLUDED_)

186
CryGame/ReadMe.txt Normal file
View File

@@ -0,0 +1,186 @@
CryGame.dll:
============
possible cleanups:
* remove IGame::Run()
* remove IGame::SetTerrainSurface()
* remove IGame::CreateTagPoint()
* remove IGame::CreateTagPoint()
* remove IGame::CreateTagPoint(), GetTagPoint(), RemoveTagPoint()
* remove IGame::CreateArea()
* remove IGame::DeleteArea()
* remove IGame::GetArea()
* remove weapons from IGame
* remove equipacks from IGame
* remove respawn points from IGame
* remove keycards from XPlayer (not used at all - simple)
AIHandler.cpp
AIHandler.h
* CryGame.cpp CryGame.h
CXGame implements the IGame interface
CXGame::Run() run the main loop until another subsystem force the exit
CXGame::Update() handles the updates per frame
EntityClassRegistry.cpp
EntityClassRegistry.h
Flock.cpp
Flock.h
FlyBy.cpp
FlyBy.h
Game.cpp
Game.h
GameLoading.cpp
GameMemStats.cpp
GameObject.h
GameShared.h
IngameDialog.cpp
IngameDialog.h
IXSystem.h
LipSync.cpp
LipSync.h
MainMenu.cpp
MainMenu.h
MenuSystem.cpp
MenuSystem.h
NetEntityInfo.cpp
NetEntityInfo.h
PlayerSystem.h
ReadMe.txt this readme file
ScriptObjectAI.cpp
ScriptObjectAI.h
ScriptObjectAnimation.cpp
ScriptObjectAnimation.h
ScriptObjectBoids.cpp
ScriptObjectBoids.h
ScriptObjectClient.cpp
ScriptObjectClient.h
ScriptObjectEntity.cpp
ScriptObjectEntity.h
ScriptObjectGame.cpp
ScriptObjectGame.h
ScriptObjectGUI.cpp
ScriptObjectGUI.h
ScriptObjectInput.cpp
ScriptObjectInput.h
ScriptObjectLanguage.cpp
ScriptObjectLanguage.h
ScriptObjectMath.cpp
ScriptObjectMath.h
ScriptObjectMovie.cpp
ScriptObjectMovie.h
ScriptObjectParticle.cpp
ScriptObjectParticle.h
ScriptObjectPlayer.cpp
ScriptObjectPlayer.h
ScriptObjectScript.cpp
ScriptObjectScript.h
ScriptObjectServer.cpp
ScriptObjectServer.h
ScriptObjectServerSlot.cpp
ScriptObjectServerSlot.h
ScriptObjectSound.cpp
ScriptObjectSound.h
ScriptObjectSpectator.cpp
ScriptObjectSpectator.h
ScriptObjectStream.cpp
ScriptObjectStream.h
ScriptObjectVector.h
ScriptObjectVehicle.cpp
ScriptObjectVehicle.h
ScriptObjectWeapon.cpp
ScriptObjectWeapon.h
ScriptTimerMgr.cpp
ScriptTimerMgr.h
Spectator.cpp
Spectator.h
StdAfx.cpp
StdAfx.h
StringTableMgr.cpp
StringTableMgr.h
TagPoint.h
UI.cpp
UI.h
UIHud.cpp
UIHud.h
vssver.scc
XArea.cpp
XArea.h
XButton.cpp
XButton.h
XClient.cpp
XClient.h
XClientSnapshot.cpp
XClientSnapshot.h
XControlPage.cpp
XControlPage.h
XDemoMgr.cpp
XDemoMgr.h
XEditBox.cpp
XEditBox.h
XEntityProcessingCmd.cpp
XEntityProcessingCmd.h
XFireMap.cpp
XFireMap.h
XGameStuff.cpp
XGameStuff.h
XGUIControl.cpp
XGUIControl.h
XHud.cpp
XHud.h
XListBox.cpp
XListBox.h
XNetwork.cpp
XNetwork.h
XObjectProxy.cpp
XObjectProxy.h
XPath.cpp
XPath.h
XPathSystem.cpp
XPathSystem.h
XPlayer.cpp
XPlayer.h
XPlayerCamera.cpp
XplayerVehicle.cpp
XPullDownMenu.cpp
XPullDownMenu.h
XPuppetProxy.cpp
XPuppetProxy.h
XServer.cpp
XServer.h
XServerRules.cpp
XServerRules.h
XServerSlot.cpp
XServerSlot.h
XSmthBuffer.cpp
XSmthBuffer.h
XSnapshot.cpp
XSnapshot.h
XStatic.cpp
XStatic.h
XSurfaceMgr.cpp
XSurfaceMgr.h
XSystemBase.cpp
XSystemBase.h
XSystemClient.cpp
XSystemClient.h
XSystemDummy.cpp
XSystemDummy.h
XSystemServer.cpp
XSystemServer.h
XVehicle.cpp
XVehicle.h
XVehicleProxy.cpp
XVehicleProxy.h
XVehicleSystem.cpp
XVehicleSystem.h
XWeapon.cpp
XWeapon.h
XWeaponSystem.cpp
XWeaponSystem.h

1451
CryGame/ScriptObjectAI.cpp Normal file

File diff suppressed because it is too large Load Diff

93
CryGame/ScriptObjectAI.h Normal file
View File

@@ -0,0 +1,93 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectAI.h: interface for the CScriptObjectAI class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTAI_H__3D4BC3E5_B60C_40DC_A819_17EE0F04C00A__INCLUDED_)
#define AFX_SCRIPTOBJECTAI_H__3D4BC3E5_B60C_40DC_A819_17EE0F04C00A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IScriptSystem.h>
#include <IEntitySystem.h>
#include <IAISystem.h>
#include <ILog.h>
#include <map>
#include <_ScriptableEx.h>
struct IGoalPipe;
/*! This class implements script-functions for manipulating the AI system
REMARKS:
After initialization of the script-object it will be globally accessable through scripts using the namespace "AI".
Example:
AI.CreateGoalPipe("some_pipe");
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectAI :
public _ScriptableEx<CScriptObjectAI>
{
public:
int SoundEvent(IFunctionHandler *pH);
int PushGoal(IFunctionHandler *pH);
int CreateGoalPipe( IFunctionHandler *pH);
void Init(IScriptSystem *, ISystem *, CXGame *);
CScriptObjectAI();
virtual ~CScriptObjectAI();
static void InitializeTemplate(IScriptSystem *pSS);
private:
IAISystem *m_pAISystem;
ILog *m_pLog;
IEntitySystem *m_pEntitySystem;
ISoundSystem *m_pSoundSystem;
CXGame *m_pGame;
public:
//! logs into special AI file :)
int Log(IFunctionHandler * pH);
//! sends signal to ai objects
int Signal(IFunctionHandler * pH);
//! gets how many agents are in the specified group
int GetGroupCount(IFunctionHandler * pH);
int GetAttentionTargetOf(IFunctionHandler * pH);
int ReloadAll(IFunctionHandler * pH);
int MakePuppetIgnorant(IFunctionHandler * pH);
int FreeSignal(IFunctionHandler * pH);
int SetAssesmentMultiplier(IFunctionHandler * pH);
int FindObjectOfType(IFunctionHandler * pH);
int GetGroupOf(IFunctionHandler * pH);
int GetAnchor(IFunctionHandler * pH);
int GetPerception(IFunctionHandler * pH);
int RegisterWithAI(IFunctionHandler * pH);
int AIBind(IFunctionHandler * pH);
int CreateBoundObject(IFunctionHandler *pH);
int Cloak(IFunctionHandler * pH);
int DeCloak(IFunctionHandler * pH);
int ProjectileShoot(IFunctionHandler * pH);
int SetTheSkip(IFunctionHandler * pH);
int SetAllowedDeathCount(IFunctionHandler * pH);
int Checkpoint(IFunctionHandler * pH);
int RegisterPlayerHit(IFunctionHandler * pH);
int FireOverride(IFunctionHandler * pH);
int SetSpeciesThreatMultiplier(IFunctionHandler * pH);
int EnablePuppetMovement(IFunctionHandler * pH);
int IsMoving(IFunctionHandler * pH);
int EnableNodesInSphere(IFunctionHandler * pH);
int GetStats(IFunctionHandler * pH);
};
#endif // !defined(AFX_SCRIPTOBJECTAI_H__3D4BC3E5_B60C_40DC_A819_17EE0F04C00A__INCLUDED_)

View File

@@ -0,0 +1,106 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectAdvCamSystem.cpp
//
// Description:
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "scriptobjectAdvCamSystem.h"
#include "AdvCamSystem.h"
//////////////////////////////////////////////////////////////////////////
_DECLARE_SCRIPTABLEEX(CScriptObjectAdvCamSystem)
//////////////////////////////////////////////////////////////////////////
void CScriptObjectAdvCamSystem::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectAdvCamSystem>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectAdvCamSystem,SetPlayerA);
REG_FUNC(CScriptObjectAdvCamSystem,GetPlayerA);
REG_FUNC(CScriptObjectAdvCamSystem,SetPlayerB);
REG_FUNC(CScriptObjectAdvCamSystem,GetPlayerB);
REG_FUNC(CScriptObjectAdvCamSystem,SetMaxRadius);
REG_FUNC(CScriptObjectAdvCamSystem,SetMinRadius);
}
bool CScriptObjectAdvCamSystem::Create(IScriptSystem *pScriptSystem, CAdvCamSystem *pAdvCamSystem)
{
m_pAdvCamSystem=pAdvCamSystem;
Init(pScriptSystem, this);
m_pScriptThis->RegisterParent(this);
// Function-Registration
return true;
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectAdvCamSystem::SetPlayerA(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int host=0;
if(pH->GetParam(1,host))
m_pAdvCamSystem->m_eiPlayerA=host;
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectAdvCamSystem::GetPlayerA(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pAdvCamSystem->m_eiPlayerA);
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectAdvCamSystem::SetPlayerB(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int host=0;
if(pH->GetParam(1,host))
m_pAdvCamSystem->m_eiPlayerB=host;
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectAdvCamSystem::GetPlayerB(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pAdvCamSystem->m_eiPlayerB);
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectAdvCamSystem::SetMaxRadius(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
float radius = 0;
if(pH->GetParam(1, radius))
m_pAdvCamSystem->SetMaxRadius(radius);
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectAdvCamSystem::SetMinRadius(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
float radius = 0;
if(pH->GetParam(1, radius))
m_pAdvCamSystem->SetMinRadius(radius);
return pH->EndFunction();
}

View File

@@ -0,0 +1,56 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SCRIPTOBJECTADVCAMSYSTEM_H_
#define _SCRIPTOBJECTADVCAMSYSTEM_H_
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CAdvCamSystem;
/*! In this class are all AdvCamSystem-related script-functions implemented.
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectAdvCamSystem : public _ScriptableEx<CScriptObjectAdvCamSystem>, public IScriptObjectSink
{
public:
//! constructor
CScriptObjectAdvCamSystem( void ) {}
//! destructor
virtual ~CScriptObjectAdvCamSystem( void ) {}
//!
bool Create(IScriptSystem *pScriptSystem, CAdvCamSystem *pAdvCamSystem);
//!
void OnRelease()
{
m_pScriptThis=NULL;
delete this;
}
// is called from CXGame::Reset() to add the scripting
static void InitializeTemplate(IScriptSystem *pSS);
// script functions -----------------------------------------------
int SetPlayerA( IFunctionHandler *pH );
int GetPlayerA( IFunctionHandler *pH );
int SetPlayerB( IFunctionHandler *pH );
int GetPlayerB( IFunctionHandler *pH );
int SetMaxRadius( IFunctionHandler *pH );
int SetMinRadius( IFunctionHandler *pH );
private:
CAdvCamSystem *m_pAdvCamSystem;
};
#endif //_SCRIPTOBJECTADVCAMSYSTEM_H_

View File

@@ -0,0 +1,455 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: scriptobjectboids.cpp
// Version: v1.00
// Created: 17/5/2002 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "scriptobjectboids.h"
#include "ScriptObjectVector.h"
#include "Flock.h"
_DECLARE_SCRIPTABLEEX(CScriptObjectBoids)
//////////////////////////////////////////////////////////////////////////
CScriptObjectBoids::CScriptObjectBoids(void)
{
}
//////////////////////////////////////////////////////////////////////////
CScriptObjectBoids::~CScriptObjectBoids(void)
{
}
//////////////////////////////////////////////////////////////////////////
void CScriptObjectBoids::Init(IScriptSystem *pScriptSystem, ISystem *pSystem, CFlockManager *flockMgr)
{
m_pSystem = pSystem;
m_pScriptSystem = pScriptSystem;
m_flockMgr = flockMgr;
InitGlobal(pScriptSystem,"Boids",this);
}
void CScriptObjectBoids::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectBoids>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectBoids,CreateBirdsFlock);
REG_FUNC(CScriptObjectBoids,CreateFishFlock);
REG_FUNC(CScriptObjectBoids,CreateBugsFlock);
REG_FUNC(CScriptObjectBoids,SetFlockPos);
REG_FUNC(CScriptObjectBoids,SetFlockName);
REG_FUNC(CScriptObjectBoids,SetFlockParams);
REG_FUNC(CScriptObjectBoids,RemoveFlock );
REG_FUNC(CScriptObjectBoids,EnableFlock );
REG_FUNC(CScriptObjectBoids,SetFlockPercentEnabled );
}
int CScriptObjectBoids::CommonCreateFlock( IFunctionHandler *pH,int type )
{
CHECK_PARAMETERS(4);
CScriptObjectVector oVec(m_pScriptSystem,true);
_SmartScriptObject pParams(m_pScriptSystem,true);
IEntity *pEntity = 0;
int nEntityId = 0;
const char *str;
int flock_handle = 0;
int count = 0;
Vec3d pos;
string model;
SBoidContext bc;
CFlock *flock = m_flockMgr->CreateFlock( (EFlockType)type );
if (!flock)
{
return pH->EndFunction(0);
}
flock->GetBoidSettings( bc );
flock_handle = flock->GetId();
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(pH->GetParam(1,str))
{
flock->SetName( str );
}
else
m_pScriptSystem->RaiseError( "<CreateFlock> parameter 1(name) not specified or nil" );
//////////////////////////////////////////////////////////////////////////
// 2nd param position.
//////////////////////////////////////////////////////////////////////////
if(pH->GetParam(2,oVec))
{
flock->SetPos( oVec.Get() );
}
else
m_pScriptSystem->RaiseError( "<CreateFlock> parameter 2(pos) not specified or nil" );
//////////////////////////////////////////////////////////////////////////
// 3rd param params, entity id.
//////////////////////////////////////////////////////////////////////////
if(pH->GetParam(3,nEntityId))
{
pEntity = m_pSystem->GetIEntitySystem()->GetEntity(nEntityId);
flock->SetEntity( pEntity );
}
//////////////////////////////////////////////////////////////////////////
// 4rd param params.
//////////////////////////////////////////////////////////////////////////
if(pH->GetParam(4,pParams))
{
SBoidsCreateContext ctx;
if (ReadParamsTable( pParams,bc,ctx ))
{
bc.entity = pEntity;
flock->SetBoidSettings( bc );
flock->CreateBoids( ctx );
}
}
else
m_pScriptSystem->RaiseError( "<CreateFlock> parameter 3(params table) not specified or nil" );
// return.
return pH->EndFunction(flock_handle);
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::CreateBirdsFlock(IFunctionHandler *pH)
{
return CommonCreateFlock( pH,EFLOCK_BIRDS );
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::CreateFishFlock(IFunctionHandler *pH)
{
return CommonCreateFlock( pH,EFLOCK_FISH );
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::CreateBugsFlock(IFunctionHandler *pH)
{
return CommonCreateFlock( pH,EFLOCK_BUGS );
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::SetFlockPos(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
CScriptObjectVector oVec(m_pScriptSystem,true);
int flock_handle;
CFlock *flock;
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(!pH->GetParam(1,flock_handle))
m_pScriptSystem->RaiseError( "<SetFlockPos> parameter 1(flock_handle) not specified or nil" );
flock = m_flockMgr->GetFlock(flock_handle);
if (!flock)
return pH->EndFunction();
//////////////////////////////////////////////////////////////////////////
// 2nd param position.
//////////////////////////////////////////////////////////////////////////
if(pH->GetParam(2,oVec))
{
flock->SetPos( oVec.Get() );
}
else
m_pScriptSystem->RaiseError( "<SetFlockPos> parameter 2(pos) not specified or nil" );
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::SetFlockName(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2)
int flock_handle;
const char *name;
CFlock *flock;
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(!pH->GetParam(1,flock_handle))
m_pScriptSystem->RaiseError( "<SetFlockName> parameter 1(flock_handle) not specified or nil" );
flock = m_flockMgr->GetFlock(flock_handle);
if (!flock)
return pH->EndFunction();
//////////////////////////////////////////////////////////////////////////
// 2nd param position.
//////////////////////////////////////////////////////////////////////////
if(pH->GetParam(2,name))
{
flock->SetName( name );
}
else
m_pScriptSystem->RaiseError( "<SetFlockName> parameter 2(name) not specified or nil" );
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::SetFlockParams(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
CScriptObjectVector oVec(m_pScriptSystem,true);
_SmartScriptObject pParams(m_pScriptSystem,true);
int flock_handle;
CFlock *flock;
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(!pH->GetParam(1,flock_handle))
m_pScriptSystem->RaiseError( "<SetFlockParams> parameter 1(flock_handle) not specified or nil" );
flock = m_flockMgr->GetFlock(flock_handle);
if (!flock)
return pH->EndFunction();
string currModel = flock->GetModelName();
int currCount = flock->GetBoidsCount();
SBoidContext bc;
flock->GetBoidSettings(bc);
int count = 0;
string model;
//////////////////////////////////////////////////////////////////////////
// 2nd param position.
//////////////////////////////////////////////////////////////////////////
if (pH->GetParam(2,pParams))
{
SBoidsCreateContext ctx;
if (ReadParamsTable( pParams,bc,ctx ))
{
flock->SetBoidSettings( bc );
string model = "";
if (!ctx.models.empty())
model = ctx.models[0];
if ((!model.empty() && stricmp(model.c_str(),currModel.c_str()) == 0) ||
(ctx.boidsCount > 0 && ctx.boidsCount != currCount))
{
flock->CreateBoids( ctx );
}
}
}
else
m_pScriptSystem->RaiseError( "<SetFlockParams> parameter 2(params table) not specified or nil" );
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::RemoveFlock(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int flock_handle;
CFlock *flock;
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(!pH->GetParam(1,flock_handle))
m_pScriptSystem->RaiseError( "<RemoveFlock> parameter 1(flock_handle) not specified or nil" );
flock = m_flockMgr->GetFlock(flock_handle);
if (!flock)
return pH->EndFunction();
m_flockMgr->RemoveFlock( flock );
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectBoids::EnableFlock(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int flock_handle;
bool bEnable = true;
CFlock *flock;
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(!pH->GetParam(1,flock_handle))
m_pScriptSystem->RaiseError( "<EnableFlock> parameter 1(flock_handle) not specified or nil" );
flock = m_flockMgr->GetFlock(flock_handle);
if (!flock)
return pH->EndFunction();
if(!pH->GetParam(2,bEnable))
m_pScriptSystem->RaiseError( "<EnableFlock> parameter 2 (bEnable) not specified or nil" );
flock->SetEnabled( bEnable );
return pH->EndFunction();
}
int CScriptObjectBoids::SetFlockPercentEnabled(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int flock_handle;
int percent = 100;
CFlock *flock;
//////////////////////////////////////////////////////////////////////////
// 1st param name.
//////////////////////////////////////////////////////////////////////////
if(!pH->GetParam(1,flock_handle))
m_pScriptSystem->RaiseError( "<SetFlockPercentEnabled> parameter 1(flock_handle) not specified or nil" );
flock = m_flockMgr->GetFlock(flock_handle);
if (!flock)
return pH->EndFunction();
if(!pH->GetParam(2,percent))
m_pScriptSystem->RaiseError( "<SetFlockPercentEnabled> parameter 2 (percent) not specified or nil" );
flock->SetPercentEnabled( percent );
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
bool CScriptObjectBoids::ReadParamsTable(IScriptObject *pTable, struct SBoidContext &bc,SBoidsCreateContext &ctx )
{
CScriptObjectVector oVec(m_pScriptSystem,true);
pTable->BeginSetGetChain();
float fval;
const char *str;
/*
CXmlTemplate::AddParam( m_paramsTemplate,"BirdSize",bc.boidScale );
CXmlTemplate::AddParam( m_paramsTemplate,"MinHeight",bc.MinHeight );
CXmlTemplate::AddParam( m_paramsTemplate,"MaxHeight",bc.MaxHeight );
CXmlTemplate::AddParam( m_paramsTemplate,"MinAttractDist",bc.MinAttractDistance );
CXmlTemplate::AddParam( m_paramsTemplate,"MaxAttractDist",bc.MaxAttractDistance );
CXmlTemplate::AddParam( m_paramsTemplate,"MinSpeed",bc.MinSpeed );
CXmlTemplate::AddParam( m_paramsTemplate,"MaxSpeed",bc.MaxSpeed );
CXmlTemplate::AddParam( m_paramsTemplate,"FactorAlign",bc.factorAlignment );
CXmlTemplate::AddParam( m_paramsTemplate,"FactorCohesion",bc.factorCohesion );
CXmlTemplate::AddParam( m_paramsTemplate,"FactorSeparation",bc.factorSeparation );
CXmlTemplate::AddParam( m_paramsTemplate,"FactorOrigin",bc.factorAttractToOrigin );
CXmlTemplate::AddParam( m_paramsTemplate,"FactorHeight",bc.factorKeepHeight );
CXmlTemplate::AddParam( m_paramsTemplate,"FactorAvoidLand",bc.factorAvoidLand );
CXmlTemplate::AddParam( m_paramsTemplate,"FovAngle",(float)acos(bc.cosFovAngle)/PI*180.0f );
CXmlTemplate::AddParam( m_paramsTemplate,"MaxAnimSpeed",bc.MaxAnimationSpeed );
CXmlTemplate::AddParam( m_paramsTemplate,"FollowPlayer",bc.followPlayer );
CXmlTemplate::AddParam( m_paramsTemplate,"NoLanding",bc.noLanding );
CXmlTemplate::AddParam( m_paramsTemplate,"AvoidObstacles",bc.avoidObstacles );
CXmlTemplate::AddParam( m_paramsTemplate,"MaxViewDistance",bc.maxVisibleDistance );
*/
ctx.models.clear();
ctx.boidsCount = 0;
pTable->GetValueChain( "count",ctx.boidsCount );
if (pTable->GetValueChain( "model",str ))
{
ctx.models.push_back(str);
}
if (pTable->GetValueChain( "model1",str ))
{
if (strlen(str) > 0)
ctx.models.push_back(str);
}
if (pTable->GetValueChain( "model2",str ))
{
if (strlen(str) > 0)
ctx.models.push_back(str);
}
if (pTable->GetValueChain( "model3",str ))
{
if (strlen(str) > 0)
ctx.models.push_back(str);
}
if (pTable->GetValueChain( "model4",str ))
{
if (strlen(str) > 0)
ctx.models.push_back(str);
}
if (pTable->GetValueChain( "character",str ))
{
ctx.characterModel = str;
}
if (pTable->GetValueChain( "animation",str ))
{
ctx.animation = str;
}
pTable->GetValueChain( "behavior",bc.behavior );
pTable->GetValueChain( "boid_mass",bc.fBoidMass);
pTable->GetValueChain( "boid_size",bc.boidScale );
pTable->GetValueChain( "min_height",bc.MinHeight );
pTable->GetValueChain( "max_height",bc.MaxHeight );
pTable->GetValueChain( "min_attract_distance",bc.MinAttractDistance );
pTable->GetValueChain( "max_attract_distance",bc.MaxAttractDistance );
pTable->GetValueChain( "min_speed",bc.MinSpeed );
pTable->GetValueChain( "max_speed",bc.MaxSpeed );
pTable->GetValueChain( "factor_align",bc.factorAlignment );
pTable->GetValueChain( "factor_cohesion",bc.factorCohesion );
pTable->GetValueChain( "factor_separation",bc.factorSeparation );
pTable->GetValueChain( "factor_origin",bc.factorAttractToOrigin );
pTable->GetValueChain( "factor_keep_height",bc.factorKeepHeight );
pTable->GetValueChain( "factor_avoid_land",bc.factorAvoidLand );
pTable->GetValueChain( "max_anim_speed",bc.MaxAnimationSpeed );
pTable->GetValueChain( "follow_player",bc.followPlayer );
pTable->GetValueChain( "no_landing",bc.noLanding );
pTable->GetValueChain( "avoid_obstacles",bc.avoidObstacles );
pTable->GetValueChain( "max_view_distance",bc.maxVisibleDistance );
pTable->GetValueChain( "spawn_radius",bc.fSpawnRadius);
//pTable->GetValueChain( "boid_radius",bc.fBoidRadius);
pTable->GetValueChain( "gravity_at_death",bc.fGravity);
pTable->GetValueChain( "boid_mass",bc.fBoidMass);
if (pTable->GetValueChain( "fov_angle",fval ))
bc.cosFovAngle = cry_cosf(fval*gf_PI/180.0f);
pTable->EndSetGetChain();
return true;
}

105
CryGame/ScriptObjectBoids.h Normal file
View File

@@ -0,0 +1,105 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: scriptobjectboids.h
// Version: v1.00
// Created: 17/5/2002 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __scriptobjectboids_h__
#define __scriptobjectboids_h__
#if _MSC_VER > 1000
#pragma once
#endif
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
// forward declarations.
class CFlockManager;
struct SBoidsCreateContext;
/** Script object providing LUA acess to FlockManager.
*/
class CScriptObjectBoids : public _ScriptableEx<CScriptObjectBoids>
{
public:
CScriptObjectBoids(void);
virtual ~CScriptObjectBoids(void);
void Init(IScriptSystem *pScriptSystem, ISystem *pSystem, CFlockManager *flockMgr);
/** Create new birds flock.
params: name,pos,params_table
return: flock_handle
*/
int CreateBirdsFlock(IFunctionHandler *pH);
/** Create new fishes flock.
params: name,pos,params_table
return: flock_handle
*/
int CreateFishFlock(IFunctionHandler *pH);
/** Create new flock of bugs.
params: name,pos,params_table
return: flock_handle
*/
int CreateBugsFlock(IFunctionHandler *pH);
/** Move flock to a new position.
params: flock_handle,pos
return: void
*/
int SetFlockPos(IFunctionHandler *pH);
/** Assign to flock a new name.
params: flock_handle,name
return: void
*/
int SetFlockName(IFunctionHandler *pH);
/** Change parameters of flock.
params: flock_handle,params_table
return: void
*/
int SetFlockParams(IFunctionHandler *pH);
/** Remove flock.
params: flock_handle
return: void
*/
int RemoveFlock(IFunctionHandler *pH);
/** Enables/Disables flock.
params: flock_handle,bEnable
return: void
*/
int EnableFlock(IFunctionHandler *pH);
/** Set flock percentage of visibility.
params: flock_handle,percent (0-100)
return: void
*/
int SetFlockPercentEnabled(IFunctionHandler *pH);
static void InitializeTemplate(IScriptSystem *pSS);
private:
bool ReadParamsTable( IScriptObject *pTable, struct SBoidContext &bc,SBoidsCreateContext &ctx );
int CommonCreateFlock( IFunctionHandler *pH,int type );
ISystem *m_pSystem;
IScriptSystem *m_pScriptSystem;
CFlockManager *m_flockMgr;
};
#endif // __scriptobjectboids_h__

View File

@@ -0,0 +1,540 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectClient.cpp
//
// Description:
// ScriptObjectClient.cpp: implementation of the CScriptObjectClient class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ScriptObjectClient.h"
#include "XClient.h"
#include "XClient.h"
//////////////////////////////////////////////////////////////////////
_DECLARE_SCRIPTABLEEX(CScriptObjectClient)
//////////////////////////////////////////////////////////////////////
CScriptObjectClient::CScriptObjectClient()
{
m_pClient=NULL;
}
//////////////////////////////////////////////////////////////////////
CScriptObjectClient::~CScriptObjectClient()
{
if(m_pSoundEventPos)
m_pSoundEventPos->Release();
}
//////////////////////////////////////////////////////////////////////
void CScriptObjectClient::Create(IScriptSystem *pScriptSystem,CXGame *pGame,CXClient *pClient)
{
m_pGame=pGame;
m_pClient=pClient;
InitGlobal(pScriptSystem,"Client",this);
m_pSoundEventPos=pScriptSystem->CreateObject();
}
//////////////////////////////////////////////////////////////////////
void CScriptObjectClient::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectClient>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectClient,GetGameStartTime);
REG_FUNC(CScriptObjectClient,GetGameState);
REG_FUNC(CScriptObjectClient,GetGameStateString);
REG_FUNC(CScriptObjectClient,CallVote);
REG_FUNC(CScriptObjectClient,Vote);
REG_FUNC(CScriptObjectClient,Kill);
REG_FUNC(CScriptObjectClient,JoinTeamRequest);
REG_FUNC(CScriptObjectClient,SendCommand);
REG_FUNC(CScriptObjectClient,GetPing);
REG_FUNC(CScriptObjectClient,Say);
REG_FUNC(CScriptObjectClient,SayTeam);
REG_FUNC(CScriptObjectClient,SayOne);
REG_FUNC(CScriptObjectClient,GetSoundsEventsPos);
REG_FUNC(CScriptObjectClient,SetName);
REG_FUNC(CScriptObjectClient,SetBitsPerSecond);
REG_FUNC(CScriptObjectClient,SetUpdateRate);
REG_FUNC(CScriptObjectClient,GetServerCPUTargetName);
REG_FUNC(CScriptObjectClient,GetServerOSTargetName);
pSS->SetGlobalValue("CGS_INPROGRESS", 0);
pSS->SetGlobalValue("CGS_COUNTDOWN", 1);
pSS->SetGlobalValue("CGS_PREWAR", 2);
pSS->SetGlobalValue("CGS_INTERMISSION", 3);
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetGameStartTime(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction((int)m_pClient->m_fGameLastTimeReceived - m_pClient->m_nGameLastTime);
}
/*!return the current gamestate (PREWAR,INTERMISSION etc...)
return the current game state
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetGameState(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pClient->m_nGameState);
}
/*!return the name of the current gamestate (PREWAR,INTERMISSION etc...)
return the string containing the name of the current game state
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetGameStateString(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
if(m_pClient->m_nGameState==CGS_INPROGRESS)
{
int curtime = (int)(m_pGame->m_pSystem->GetITimer()->GetCurrTime()-m_pClient->m_fGameLastTimeReceived)+m_pClient->m_nGameLastTime;
char buf[100];
sprintf(buf, "%2d:%02d", curtime/60, curtime%60);
return pH->EndFunction(buf);
}
else if(m_pClient->m_nGameState==CGS_PREWAR)
{
return pH->EndFunction("PREWAR");
}
else
{
return pH->EndFunction("");
};
}
/*!call a vote during a multiplayer game
@param command symbolic name of the command
@param argument of the command
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::CallVote(IFunctionHandler *pH)
{
const char *command = "", *arg1 = "";
switch(pH->GetParamCount())
{
case 1:
pH->GetParam(1, command);
break;
case 2:
pH->GetParam(1, command);
pH->GetParam(2, arg1);
break;
default:
m_pGame->m_pSystem->GetILog()->Log("wrong number of parameters to callvote");
return pH->EndFunction();
};
CStream stm;
stm.Write(command);
stm.Write(arg1);
m_pClient->SendReliableMsg(XCLIENTMSG_CALLVOTE, stm);
return pH->EndFunction();
}
/*!send a vote to the server during a multiplayer game
@param vote string containing "yes" or "no"
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::Vote(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *vote = "";
pH->GetParam(1, vote);
CStream stm;
if(stricmp(vote, "yes")==0)
{
stm.Write(1);
m_pClient->SendReliableMsg(XCLIENTMSG_VOTE, stm);
}
else if(stricmp(vote, "no")==0)
{
stm.Write(0);
m_pClient->SendReliableMsg(XCLIENTMSG_VOTE, stm);
}
else
{
m_pGame->m_pSystem->GetILog()->Log("vote yes or no");
};
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::Kill(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
CStream stm;
m_pClient->SendReliableMsg(XCLIENTMSG_KILL, stm);
return pH->EndFunction();
}
/*!send a request to the server to join a specified team
if the team is "spectators" the caller client will leave the
game and become a spectator.
@param sTeamName team name
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::JoinTeamRequest(IFunctionHandler *pH)
{
//CHECK_PARAMETERS(1);
if(pH->GetParamCount()>0)
{
const char *sTeamName;
const char *sClass="";
pH->GetParam(1,sTeamName);
int nTeamId=m_pClient->m_pISystem->GetTeamId(sTeamName);
if (nTeamId>=0)
{
if(pH->GetParamCount()>1)
{
pH->GetParam(2,sClass);
}
CStream stm;
stm.Write((BYTE)nTeamId);
stm.Write(sClass);
m_pClient->SendReliableMsg(XCLIENTMSG_JOINTEAMREQUEST, stm);
}
else
{
m_pGame->m_pLog->Log("team \"%s\" doesn't exist!", sTeamName);
};
}
else
{
IConsole *pConsole=m_pGame->GetSystem()->GetIConsole();
pConsole->PrintLine("(JoinTeamRequest/team)the command require at least one parameter");
}
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::SetBitsPerSecond(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int bits;
if(pH->GetParam(1,bits))
m_pClient->SetBitsPerSecond(bits);
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::SetUpdateRate(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int countpersec;
if(pH->GetParam(1,countpersec))
m_pClient->SetUpdateRate(countpersec);
return pH->EndFunction();
}
/*!(LEGACY)send a string command to the server
@param sString the string to express the command
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::SendCommand(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *sString;
if(pH->GetParam(1,sString))
m_pClient->SendCommand(sString);
return pH->EndFunction();
}
/*!return the ping of the local client
@return the current ping in milliseconds
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetPing(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pClient->GetPing());
}
/*!send a string to the server in order to broadcast it to alla othe client
used to implement in-game chat
@param sString the string to broadcast
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::Say(IFunctionHandler *pH)
{
int iParamCount = pH->GetParamCount();
if (iParamCount < 1)
{
return pH->EndFunction();
}
char *szParam = 0;
string szText;
for(int i = 1; i <= iParamCount; i++)
{
pH->GetParam(i, szParam);
if (i != 1)
{
szText.push_back(' ');
}
if (szParam)
{
szText = szText + szParam;
}
}
char szTrimmed[65] = {0};
strncpy(szTrimmed, szText.c_str(), 64);
TextMessage pTextMessage;
pTextMessage.cMessageType = CMD_SAY;
pTextMessage.uiTarget = 0;
// pTextMessage.stmPayload.Write(szTrimmed);
pTextMessage.m_sText=szTrimmed;
m_pClient->SendTextMessage(pTextMessage);
return pH->EndFunction();
}
/*!send a string to the server in order to broadcast it to all member of the local client team
used to implement in-game chat
@param sString the string to broadcast
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::SayTeam(IFunctionHandler *pH)
{
int iParamCount = pH->GetParamCount();
if (iParamCount < 1)
{
return pH->EndFunction();
}
int iTeamID = m_pClient->m_pISystem->GetEntityTeam(m_pClient->GetPlayerId());
if (iTeamID == -1 || iTeamID == SPECTATORS_TEAM)
{
m_pGame->m_pLog->Log("sayteam: you are not in a team or spectating!");
return pH->EndFunctionNull();
}
// don't send any team messages from non-team games (FFA)
char sTeamName[256];
if (m_pClient->m_pISystem->GetTeamName(iTeamID, sTeamName) && strcmp(sTeamName, "players") == 0)
{
m_pGame->m_pLog->Log("sayteam: used in a non-team game!");
return pH->EndFunctionNull();
}
char *szParam;
string szText;
for(int i = 1; i <= iParamCount; i++)
{
pH->GetParam(i, szParam);
if (i != 1)
{
szText.push_back(' ');
}
if (szParam)
{
szText = szText + szParam;
}
}
char szTrimmed[65] = {0};
strncpy(szTrimmed, szText.c_str(), 64);
TextMessage pTextMessage;
pTextMessage.cMessageType = CMD_SAY_TEAM;
pTextMessage.uiTarget = iTeamID;
// pTextMessage.stmPayload.Write(szTrimmed);
pTextMessage.m_sText=szTrimmed;
m_pClient->SendTextMessage(pTextMessage);
return pH->EndFunction();
}
/*!send a string to the server in order to deliver it to a cetain player
used to implement in-game chat
@param target entity id or name of the target
@param sString the string to broadcast
*/
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::SayOne(IFunctionHandler *pH)
{
int iParamCount = pH->GetParamCount();
if (iParamCount < 2)
{
return pH->EndFunction();
}
int iEntityID = -1;
char *szEntityName = 0;
IEntity *pEntity = 0;
IXSystem *pXSystem = m_pClient->m_pISystem;
if (pH->GetParam(1, iEntityID))
{
pEntity = pXSystem->GetEntity(iEntityID);
}
else if (pH->GetParam(1, szEntityName))
{
pEntity = pXSystem->GetEntity(szEntityName);
}
if (!pEntity)
{
m_pClient->AddHudMessage("Player not found!", 3);
m_pGame->m_pLog->Log("Player not found!");
return pH->EndFunction();
}
char *szParam;
string szText;
for(int i = 2; i <= iParamCount; i++)
{
pH->GetParam(i, szParam);
if (i != 2)
{
szText.push_back(' ');
}
if (szParam)
{
szText = szText + szParam;
}
}
char szTrimmed[65] = {0};
strncpy(szTrimmed, szText.c_str(), 64);
TextMessage pTextMessage;
pTextMessage.cMessageType = CMD_SAY_ONE;
pTextMessage.uiTarget = pEntity->GetId();
// pTextMessage.stmPayload.Write(szTrimmed);
pTextMessage.m_sText=szTrimmed;
m_pClient->SendTextMessage(pTextMessage);
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetSoundsEventsPos(IFunctionHandler *pH)
{
m_pSoundEventPos->SetValue("front",m_pClient->m_fFrontSound);
m_pSoundEventPos->SetValue("back",m_pClient->m_fBackSound);
m_pSoundEventPos->SetValue("left",m_pClient->m_fLeftSound);
m_pSoundEventPos->SetValue("right",m_pClient->m_fRightSound);
return pH->EndFunction(m_pSoundEventPos);
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::SetName(IFunctionHandler *pH)
{
if ((pH->GetParamCount() != 0) && ((pH->GetParamType(1) == svtString) || (pH->GetParamType(1) == svtNumber)))
{
const char *szName = 0;
pH->GetParam(1, szName);
if(!szName)
return pH->EndFunction();
char sTemp[65];
CXServerSlot::ConvertToValidPlayerName(szName,sTemp,sizeof(sTemp));
//CXServerSlot::ConvertToValidPlayerName(szName,sTemp);
int len = strlen(sTemp);
if(len)
{
CStream stm;
stm.Write(sTemp);
m_pGame->m_pLog->Log("Send SetName '%s'",sTemp);
m_pGame->p_name->Set(sTemp);
m_pClient->SendReliableMsg(XCLIENTMSG_NAME, stm);
return pH->EndFunction();
}
}
char nameline[64] = {0};
sprintf(nameline, "name = \"%s\"", m_pGame->p_name->GetString());
m_pGame->GetSystem()->GetIConsole()->PrintLine(nameline);
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::AIState(IFunctionHandler *pH)
{
CStream stm;
int nDummy=0;
stm.Write(nDummy);
m_pClient->SendReliableMsg(XCLIENTMSG_AISTATE, stm);
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetServerCPUTargetName(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pClient->m_GameContext.GetCPUTarget());
}
//////////////////////////////////////////////////////////////////////
int CScriptObjectClient::GetServerOSTargetName(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pClient->m_GameContext.GetOSTarget());
}

View File

@@ -0,0 +1,65 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SCRIPTOBJECTCLIENT_H_
#define _SCRIPTOBJECTCLIENT_H_
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CXClient;
class CXGame;
/*! This class implements script-functions for exposing the local client functionalities
REMARKS:
After initialization of the script-object it will be globally accessable through scripts using the namespace "Client".
This object isn't instantiated on a dedicated server
Example:
Server.SpawnEntity("Rocket");
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectClient :
public _ScriptableEx<CScriptObjectClient>
{
public:
CScriptObjectClient();
virtual ~CScriptObjectClient();
void Create(IScriptSystem *pScriptSystem,CXGame *pGame,CXClient *pClient);
static void InitializeTemplate(IScriptSystem *pSS);
int GetGameStartTime(IFunctionHandler *pH);
int GetGameState(IFunctionHandler *pH);
int GetGameStateString(IFunctionHandler *pH);
int CallVote(IFunctionHandler *pH);
int Vote(IFunctionHandler *pH);
int Kill(IFunctionHandler *pH);
int JoinTeamRequest(IFunctionHandler *pH);
int SendCommand(IFunctionHandler *pH);
int GetPing(IFunctionHandler *pH);
int Say(IFunctionHandler *pH);
int SayTeam(IFunctionHandler *pH);
int SayOne(IFunctionHandler *pH);
int SetName(IFunctionHandler *pH);
int GetSoundsEventsPos(IFunctionHandler *pH);
int SetBitsPerSecond(IFunctionHandler *pH);
int SetUpdateRate(IFunctionHandler *pH);
int GetServerCPUTargetName(IFunctionHandler *pH);
int GetServerOSTargetName(IFunctionHandler *pH);
// to sync AI state for co-op
int AIState(IFunctionHandler *pH);
private: // -------------------------------------------------------------------
CXClient * m_pClient; //!<
CXGame * m_pGame; //!<
IScriptObject * m_pSoundEventPos; //!<
};
#endif //_SCRIPTOBJECTCLIENT_H_

3926
CryGame/ScriptObjectGame.cpp Normal file

File diff suppressed because it is too large Load Diff

230
CryGame/ScriptObjectGame.h Normal file
View File

@@ -0,0 +1,230 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectGame.h: interface for the CScriptObjectGame class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTGAME_H__52FF12D6_6378_4A6E_AA1F_A7867997F86A__INCLUDED_)
#define AFX_SCRIPTOBJECTGAME_H__52FF12D6_6378_4A6E_AA1F_A7867997F86A__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
#include <ScriptObjectVector.h>
class CXGame;
#define PICK_SELONLY 0x00000001
#define PICK_SELADD 0x00000002
#define PICK_SELSUB 0x00000003
class CScriptObjectRenderer;
typedef std::vector<CScriptObjectRenderer *> SORVec;
/*! This class implements script-functions for exposing the Game functionalities
REMARKS:
After initialization of the script-object it will be globally accessable through scripts using the namespace "Game".
Example:
local players=Game.GetPlayers();
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectGame :
public _ScriptableEx<CScriptObjectGame>
{
public:
CScriptObjectGame();
virtual ~CScriptObjectGame();
void Init(IScriptSystem *pScriptSystem,CXGame *pGame);
void Reset();
void OnNETServerFound(CIPAddress &ip, SXServerInfos &pServerInfo);
void OnNETServerTimeout(CIPAddress &ip);
public:
int GetCDPath(IFunctionHandler *pH);
int GetUserName(IFunctionHandler *pH);
int ReloadMaterials(IFunctionHandler *pH);
int GetRandomRespawnPoint(IFunctionHandler *pH); //void (return vector)
int RefreshServerList(IFunctionHandler *pH); //void (return void)
int ClearServerInfo(IFunctionHandler *pH);
int GetServerInfo(IFunctionHandler *pH);
int GetServerListInfo(IFunctionHandler *pH);
// int ConnectToRConServer(IFunctionHandler *pH);
int ExecuteRConCommand(IFunctionHandler *pH);
int GetPlayers(IFunctionHandler *pH); //void (return void)
int SetHUDFont(IFunctionHandler *pH);
int GetHudStringSize(IFunctionHandler *pH);
int WriteHudNumber(IFunctionHandler *pH);
int WriteHudString(IFunctionHandler *pH);
int WriteHudStringFixed(IFunctionHandler *pH);
int GetActions(IFunctionHandler *pH);
int IsPlayer(IFunctionHandler *pH);
int GetServerList(IFunctionHandler *pH);
int __RespawnEntity(IFunctionHandler *pH);
int ListPlayers(IFunctionHandler *pH);
int CheckMap(IFunctionHandler *pH);
int GetMapDefaultMission(IFunctionHandler *pH);
int CleanUpLevel(IFunctionHandler *pH); // unload the level
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
int LoadStreamingSound(IFunctionHandler *pH);
int StopMusic(IFunctionHandler *pH);
int SetTimer(IFunctionHandler *pH);
int KillTimer(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int GetWeaponClassIDByName(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int PickEntities(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int GetEntitiesScreenSpace(IFunctionHandler *pH);
int GetPlayerEntitiesInRadius(IFunctionHandler *pH);
int DrawRadar(IFunctionHandler *pH);
int DrawHalfCircleGauge(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int ShowIngameDialog(IFunctionHandler *pH);
int HideIngameDialog(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int EnableUIOverlay(IFunctionHandler *pH);
int IsUIOverlay(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int EnableQuicksave(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int GetEntityTeam(IFunctionHandler *pH);
int GetTeamScore(IFunctionHandler *pH);
int GetTeamFlags(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int CreateVariable(IFunctionHandler *pH);//str
int SetVariable(IFunctionHandler* pH);
int RemoveVariable(IFunctionHandler *pH);//str
int GetVariable(IFunctionHandler* pH);
/////////////////////////////////////////////////////////////
int Connect(IFunctionHandler *pH);
int Reconnect(IFunctionHandler *pH);
int Disconnect(IFunctionHandler *pH);
int GetLevelList (IFunctionHandler* pH);
int LoadLevel(IFunctionHandler *pH);
int LoadLevelListen(IFunctionHandler *pH);
int LoadLevelMPServer(IFunctionHandler *pH);
int GetVersion(IFunctionHandler *pH);
int GetVersionString(IFunctionHandler *pH);
int ReloadScripts(IFunctionHandler *pH);
int Load(IFunctionHandler *pH);
int Save(IFunctionHandler *pH);
int LoadLatestCheckPoint(IFunctionHandler *pH);
int ShowSaveGameMenu(IFunctionHandler *pH);
int Quit(IFunctionHandler *pH);
int IsPointInWater(IFunctionHandler *pH);
int GetWaterHeight(IFunctionHandler *pH);
int GetTagPoint(IFunctionHandler *pH);
/////////////////////////////////////////////////////////////
int IsServer(IFunctionHandler *pH);
int IsClient(IFunctionHandler *pH);
int IsMultiplayer(IFunctionHandler *pH);
int GetMaterialIDByName(IFunctionHandler *pH);
int ReloadMaterialPhysics(IFunctionHandler *pH);
int StartRecord(IFunctionHandler *pH);
int StopRecord(IFunctionHandler *pH);
///////////////////////////////////////////////////////////////
int Say(IFunctionHandler *pH);
int SayTeam(IFunctionHandler *pH);
int SayOne(IFunctionHandler *pH);
int DisplayNetworkStats(IFunctionHandler *pH);
int ForceScoreBoard(IFunctionHandler *pH);
int GetMaterialBySurfaceID(IFunctionHandler *pH);
int ReloadWeaponScripts(IFunctionHandler *pH);
int AddWeapon(IFunctionHandler *pH);
int SetViewAngles(IFunctionHandler *pH);
int DumpEntities(IFunctionHandler *pH);
int TouchCheckPoint(IFunctionHandler *pH);
int GetSaveGameList(IFunctionHandler *pH);
int ToggleMenu(IFunctionHandler *pH);
int ShowMenu(IFunctionHandler *pH);
int HideMenu(IFunctionHandler *pH);
int IsInMenu(IFunctionHandler *pH);
// int TraceGrenade(IFunctionHandler *pH);
///NEW STUFF
int SendMessage(IFunctionHandler *pH);
int GetEntityClassIDByClassName(IFunctionHandler *pH);
int SetCameraFov(IFunctionHandler *pH);
int GetCameraFov(IFunctionHandler *pH);
int ApplyStormToEnvironment(IFunctionHandler * pH);
int CreateExplosion(IFunctionHandler *pH);
int DrawLabel(IFunctionHandler *pH);
int ForceEntitiesToSleep(IFunctionHandler *pH);
int GetInstantHit(IFunctionHandler *pH);
int GetMeleeHit(IFunctionHandler *pH);
int SaveConfiguration(IFunctionHandler *pH);
int LoadConfiguration(IFunctionHandler *pH);
int LoadConfigurationEx(IFunctionHandler *pH);
int RemoveConfiguration(IFunctionHandler *pH);
//int SetListener(IFunctionHandler *pH);
int DrawHealthBar(IFunctionHandler *pH);
int LoadScript(IFunctionHandler *pH);
int CreateRenderer(IFunctionHandler *pH);
static void InitializeTemplate(IScriptSystem *pSS);
int StartDemoPlay(IFunctionHandler *pH);
int StopDemoPlay(IFunctionHandler *pH);
int GetLevelName(IFunctionHandler *pH);
int AddCommand(IFunctionHandler *pH);
int SavePlayerPos(IFunctionHandler *pH);
int LoadPlayerPos(IFunctionHandler *pH);
int GetModsList(IFunctionHandler * pH);
int LoadMOD(IFunctionHandler * pH);
int GetCurrentModName(IFunctionHandler * pH);
private: // ------------------------------------------------------------------------------
CXGame * m_pGame;
ISystem * m_pSystem;
IConsole * m_pConsole;
IRenderer * m_pRenderer;
I3DEngine * m_p3DEngine;
IInput * m_pInput;
IEntitySystem * m_pEntitySystem;
IPhysicalWorld * m_pPhysicalWorld;
IScriptObject * m_psoNavigationPoint;
IScriptObject * m_psoVector;
SORVec m_vRenderersObjs;
CScriptObjectVector m_pGetTagPoint;
std::vector<IScriptObject*> m_pPlayersPool; //!< This is pool of script objects passed back on request for players in radius.
bool _GetProfileFileNames( IFunctionHandler *pH, string &outSystem, string &outGame, const char *insCallerName );
public: // ------------------------------------------------------------------------------
int SetThirdPerson(IFunctionHandler * pH);
int SoundEvent(IFunctionHandler * pH);
int PlaySubtitle(IFunctionHandler * pH);
};
#endif // !defined(AFX_SCRIPTOBJECTGAME_H__52FF12D6_6378_4A6E_AA1F_A7867997F86A__INCLUDED_)

View File

@@ -0,0 +1,433 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectInput.cpp
//
// Description:
// ScriptObjectInput.cpp: implementation of the CScriptObjectInput class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Game.h"
#include "ScriptObjectInput.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
_DECLARE_SCRIPTABLEEX(CScriptObjectInput)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CScriptObjectInput::CScriptObjectInput()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CScriptObjectInput::~CScriptObjectInput()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CScriptObjectInput::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectInput>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectInput,BindCommandToKey);
REG_FUNC(CScriptObjectInput,BindAction);
REG_FUNC(CScriptObjectInput,BindActionMultipleMaps);
REG_FUNC(CScriptObjectInput,ClearAction);
REG_FUNC(CScriptObjectInput,SetActionMap);
REG_FUNC(CScriptObjectInput,GetActionMaps);
REG_FUNC(CScriptObjectInput,ResetToDefaults);
REG_FUNC(CScriptObjectInput,ResetAllBindings);
REG_FUNC(CScriptObjectInput,ResetBinding);
REG_FUNC(CScriptObjectInput,GetBinding);
REG_FUNC(CScriptObjectInput,SetMouseSensitivity);
REG_FUNC(CScriptObjectInput,GetMouseSensitivity);
REG_FUNC(CScriptObjectInput,SetMouseSensitivityScale);
REG_FUNC(CScriptObjectInput,GetMouseSensitivityScale);
REG_FUNC(CScriptObjectInput,GetXKeyPressedName);
REG_FUNC(CScriptObjectInput,GetXKeyDownName);
REG_FUNC(CScriptObjectInput,ResetKeyState);
REG_FUNC(CScriptObjectInput,SetInvertedMouse);
REG_FUNC(CScriptObjectInput,GetInvertedMouse);
}
/*! Initializes the script-object and makes it available for the scripts.
@param pScriptSystem Pointer to the ScriptSystem-interface
@param pGame Pointer to the Game
@param pSystem Pointer to the System-interface
*/
void CScriptObjectInput::Init(IScriptSystem *pScriptSystem,CXGame *pGame,ISystem *pSystem)
{
m_pGame=pGame;
m_pSystem=pSystem;
m_pInput=pSystem->GetIInput();
m_pConsole=pSystem->GetIConsole();
InitGlobal(pScriptSystem,"Input",this);
}
//! Reset all bindings, and set the default ones again
int CScriptObjectInput::ResetToDefaults(IFunctionHandler *pH)
{
m_pGame->ResetInputMap();
return pH->EndFunctionNull();
}
//! Resets all bindings
int CScriptObjectInput::ResetAllBindings(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
m_pGame->GetActionMapManager()->ResetAllBindings();
return pH->EndFunction();
}
/*! Binds a key (or other input) to a certain LUA-command
@param sCmd LUA-command to execute (str)
@param sRes key which should be bound to that command (str)
@param nCex if this is 0 the command will executed each frame, only once otherwise (int)
*/
int CScriptObjectInput::BindCommandToKey(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(3);
const char *sCmd;
const char *sRes;
int nCex;
pH->GetParam(1,sCmd);
pH->GetParam(2,sRes);
pH->GetParam(3,nCex);
if (!sRes)
return pH->EndFunction();
char sTemp[256];strcpy(sTemp,sRes);
m_pConsole->CreateKeyBind(sCmd,_strlwr(sTemp),nCex?true:false);
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Binds a key (or other input) to a certain action (eg. JUMP)
@param sAction action to bind (string)
@param sKeys keys which should be bound to that action (this can be more than one, separated by |, eg LEFTCTRL|RIGHTCTRL) (str)
@param nCheckPressed if this is 0 the action will triggered each frame, only once otherwise (int) (optional parameter)
*/
int CScriptObjectInput::BindAction(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
int nNumOfParams=0;
if((nNumOfParams=pH->GetParamCount())<2){
m_pScriptSystem->RaiseError("Input:BindAction wrong number of arguments");
return pH->EndFunctionNull();
}
const char *sAction;
const char *sKeys;
const char *sActionMap=NULL;
int iKeyPos = -1;
int nCheckPressed=0;
pH->GetParam(1,sAction);
pH->GetParam(2,sKeys);
if(nNumOfParams>2)
pH->GetParam(3,sActionMap);
if (nNumOfParams>3)
pH->GetParam(4, iKeyPos);
//TRACE("BindAction %s %s %s\n",sAction,sKeys,(nCheckPressed)?"true":"false");
m_pGame->BindAction(sAction,sKeys,sActionMap, iKeyPos);
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Binds a key (or other input) to a certain action (eg. JUMP) in all action-maps associated with this action
@param sAction action to bind (string)
@param sKeys keys which should be bound to that action (this can be more than one, separated by |, eg LEFTCTRL|RIGHTCTRL) (str)
*/
int CScriptObjectInput::BindActionMultipleMaps(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(3);
const char *sAction;
const char *sKeys;
int iKeyPos = -1;
pH->GetParam(1,sAction);
pH->GetParam(2,sKeys);
pH->GetParam(3,iKeyPos);
m_pGame->BindActionMultipleMaps(sAction, sKeys, iKeyPos);
/*ActionsEnumMap &ActionsMap=m_pGame->GetActionsEnumMap();
ActionsEnumMapItor It=ActionsMap.find(sAction);
if (It!=ActionsMap.end())
{
ActionInfo &Info=It->second;
for (Vec2StrIt Itor=Info.vecSetToActionMap.begin();Itor!=Info.vecSetToActionMap.end();++Itor)
{
m_pGame->BindAction(sAction, sKeys, (*Itor).c_str());
}
}*/
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Clears a certain action (eg. JUMP) from the action map.
@param sAction action to be removed (str)
@return true if this action was found and deleted, false otherwise
*/
int CScriptObjectInput::ClearAction(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(1);
const char *sAction;
pH->GetParam(1,sAction);
m_pGame->ClearAction(sAction);
return pH->EndFunction();
// return pH->EndFunction(m_pGame->ClearAction(sAction));
}
/*! Set the current action map
@param sMapName action map name("default","zoom","vehicle" etc..)
*/
int CScriptObjectInput::SetActionMap(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(1);
const char *sMapName=NULL;
if(pH->GetParam(1,sMapName))
{
m_pGame->m_pIActionMapManager->SetActionMap(sMapName);
}
return pH->EndFunction();
//
}
class CDumpActions : public IActionMapDumpSink
{
public:
IScriptObject *m_pObj;
int m_nActions;
CDumpActions(IScriptObject *pObj)
{
m_nActions=0;
m_pObj=pObj;
}
void OnElementFound(const char *pszActionMapName, IActionMap *pActionMap)
{
m_pObj->SetAt(m_nActions, pszActionMapName);
m_nActions++;
}
};
/*! Return a table containg all action names
*/
int CScriptObjectInput::GetActionMaps(IFunctionHandler *pH)
{
if(!m_pInput) return pH->EndFunctionNull();
CHECK_PARAMETERS(0);
_SmartScriptObject pObj(m_pScriptSystem);
CDumpActions Dumper(pObj);
m_pGame->m_pIActionMapManager->GetActionMaps(&Dumper);
return pH->EndFunction(Dumper.m_pObj);
}
/*! Reset an action in a specified action map
@param pszActionMapName action map
@param nAction the action to reset
*/
int CScriptObjectInput::ResetBinding(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(2);
const char *pszActionMapName;
int nAction;
pH->GetParam(1, pszActionMapName);
pH->GetParam(2, nAction);
IActionMap *pActionMap=m_pGame->m_pIActionMapManager->GetActionMap(pszActionMapName);
if (pActionMap)
pActionMap->ResetBinding(nAction);
return pH->EndFunction();
}
/*! Get the binding of a specified action of a specified action map
@param pszActionMapName action map
@param nAction the action to reset
@return a table containing 'n' couples key-mod
key: is the key bound to this action
mod: is the modifier(this parameter is currently unused)
*/
int CScriptObjectInput::GetBinding(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(2);
const char *pszActionMapName;
int nAction;
pH->GetParam(1, pszActionMapName);
pH->GetParam(2, nAction);
IActionMap *pActionMap=m_pGame->m_pIActionMapManager->GetActionMap(pszActionMapName);
if (!pActionMap)
return pH->EndFunctionNull();
_SmartScriptObject pObj(m_pScriptSystem);
char pszKey[256];
char pszMod[256];
int nKey = 0;
int nMod = 0;
int n=1;
for (int i=0;i<MAX_BINDS_PER_ACTION;i++)
{
_SmartScriptObject pKey(m_pScriptSystem);
pActionMap->GetBinding(nAction, i, pszKey, pszMod);
pActionMap->GetBinding(nAction, i, nKey, nMod);
if (strlen(pszKey))
{
pKey->SetValue("key", pszKey);
if (strlen(pszMod))
pKey->SetValue("mod", pszMod);
else
pKey->SetToNull("mod");
pKey->SetValue("key_id", nKey);
if (nMod)
pKey->SetValue("mod_id", nMod);
else
pKey->SetToNull("mod_id");
pObj->SetAt(n, pKey);
}
n++;
}
return pH->EndFunction(pObj);
}
/*! Set the mouse sensitivity
@param fSensitivity the mouse sensitivity to be set
*/
int CScriptObjectInput::SetMouseSensitivity(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(1);
float fSensitivity;
pH->GetParam(1,fSensitivity);
if(m_pInput->GetIMouse())
m_pInput->GetIMouse()->SetSensitvity(fSensitivity);
return pH->EndFunction();
}
/*! Get the mouse sensitivity
@return the mouse sensitivity
*/
int CScriptObjectInput::GetMouseSensitivity(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunction(0);
float fSensitivity;
if(m_pInput->GetIMouse())
fSensitivity=m_pInput->GetIMouse()->GetSensitvity();
else
fSensitivity = 20.0f;
return pH->EndFunction(fSensitivity);
}
/*! Set the mouse sensitivity scale
@param fSensScale the mouse sensitivity scale to be set
*/
int CScriptObjectInput::SetMouseSensitivityScale(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(1);
float fSensScale;
pH->GetParam(1,fSensScale);
if(m_pInput->GetIMouse())
m_pInput->GetIMouse()->SetSensitvityScale(fSensScale);
return pH->EndFunction();
}
/*! Get the mouse sensitivity scale
@return the mouse sensitivity scale
*/
int CScriptObjectInput::GetMouseSensitivityScale(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunction(1);
float fSensScale;
if(m_pInput->GetIMouse())
fSensScale=m_pInput->GetIMouse()->GetSensitvityScale();
else
fSensScale = 20.0f;
return pH->EndFunction(fSensScale);
}
/*! return the name of the first xkey(mouse,joystick and mouse) pressed by the user
(this method is used to capture the input into the input configuration menu)
@return a string representing the name of the pressed action
*/
int CScriptObjectInput::GetXKeyPressedName(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
const char *pszKey=m_pInput->GetXKeyPressedName();
if (!pszKey)
return pH->EndFunctionNull();
return pH->EndFunction(pszKey);
}
/*! return the name of the first xkey(mouse,joystick and mouse) down
(this method is used to check if a key was pressed)
@return a string representing the name of the pressed action
*/
int CScriptObjectInput::GetXKeyDownName(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
const char *pszKey=m_pInput->GetKeyDownName();
if (!pszKey)
return pH->EndFunctionNull();
return pH->EndFunction(pszKey);
}
int CScriptObjectInput::ResetKeyState(IFunctionHandler *pH)
{
if(!m_pInput)
return pH->EndFunctionNull();
if (pH->GetParamCount() > 0)
{
char *szKeyName = 0;
if (pH->GetParam(1, szKeyName))
{
m_pInput->GetIKeyboard()->ClearKey(m_pInput->GetKeyID(szKeyName));
return pH->EndFunction();
}
}
m_pInput->ClearKeyState();
return pH->EndFunction();
}
/*! set the inverted mouse state
@param bEnable !=nil(enabled) nil(disabled)
*/
int CScriptObjectInput::SetInvertedMouse(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(1);
bool bEnable=false;
pH->GetParam(1,bEnable);
m_pGame->m_pIActionMapManager->SetInvertedMouse(bEnable);
return pH->EndFunction();
}
/*! return the inverted mouse state
@return !=nil(enabled) nil(disabled)
*/
int CScriptObjectInput::GetInvertedMouse(IFunctionHandler *pH)
{
if(!m_pInput)return pH->EndFunctionNull();
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pGame->m_pIActionMapManager->GetInvertedMouse());
}

View File

@@ -0,0 +1,69 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectInput.h: interface for the CScriptObjectInput class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTINPUT_H__18286CA7_21F2_45E0_9DFF_9D67F6AE3BE8__INCLUDED_)
#define AFX_SCRIPTOBJECTINPUT_H__18286CA7_21F2_45E0_9DFF_9D67F6AE3BE8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CXGame;
/*! This class implements all input-related script-functions.
REMARKS:
After initialization of the script-object it will be globally accessable through scripts using the namespace "Input".
Example:
Input:BindAction("MOVE_LEFT","a");
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectInput :
public _ScriptableEx<CScriptObjectInput>
{
public:
CScriptObjectInput();
virtual ~CScriptObjectInput();
void Init(IScriptSystem *pScriptSystem,CXGame *pGame,ISystem *pSystem);
static void InitializeTemplate(IScriptSystem *pSS);
int ResetToDefaults(IFunctionHandler *pH);
int ResetAllBindings(IFunctionHandler *pH);
int BindCommandToKey(IFunctionHandler *pH);
int BindAction(IFunctionHandler *pH);
int BindActionMultipleMaps(IFunctionHandler *pH);
//int CheckForAction(IFunctionHandler *pH);
int ClearAction(IFunctionHandler *pH);
int GetActionMaps(IFunctionHandler *pH);
int ResetBinding(IFunctionHandler *pH);
int GetBinding(IFunctionHandler *pH);
int SetActionMap(IFunctionHandler *pH);
int SetMouseSensitivity(IFunctionHandler *pH);
int GetMouseSensitivity(IFunctionHandler *pH);
int SetMouseSensitivityScale(IFunctionHandler *pH);
int GetMouseSensitivityScale(IFunctionHandler *pH);
int GetXKeyPressedName(IFunctionHandler *pH);
int GetXKeyDownName(IFunctionHandler *pH);
int ResetKeyState(IFunctionHandler *pH);
int SetInvertedMouse(IFunctionHandler *pH);
int GetInvertedMouse(IFunctionHandler *pH);
private:
CXGame *m_pGame;
ISystem *m_pSystem;
IConsole *m_pConsole;
IInput *m_pInput;
};
#endif // !defined(AFX_SCRIPTOBJECTINPUT_H__18286CA7_21F2_45E0_9DFF_9D67F6AE3BE8__INCLUDED_)

View File

@@ -0,0 +1,126 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectLanguage.cpp
//
// Description:
// ScriptObjectLanguage.cpp: implementation of the CScriptObjectLanguage class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ScriptObjectLanguage.h"
#include "StringTableMgr.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define REG_FUNC(_class,_func) _class::RegisterFunction(pSS,#_func,&_class::_func);
_DECLARE_SCRIPTABLEEX(CScriptObjectLanguage)
//////////////////////////////////////////////////////////////////////
CScriptObjectLanguage::CScriptObjectLanguage()
{
}
CScriptObjectLanguage::~CScriptObjectLanguage()
{
}
//////////////////////////////////////////////////////////////////////
void CScriptObjectLanguage::Init(IScriptSystem *pScriptSystem,CStringTableMgr *pMgr)
{
InitGlobal(pScriptSystem,"Language",this);
m_pMgr=pMgr;
}
void CScriptObjectLanguage::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectLanguage>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectLanguage,LoadStringTable);
REG_FUNC(CScriptObjectLanguage,GetEnglish);
}
//////////////////////////////////////////////////////////////////////
/*! Add a new string into the string table
@param s the new string value
@param nID the numeric id representing the string
*/
void CScriptObjectLanguage::AddString(const char *s,int nID)
{
m_pScriptThis->SetValue(s,nID);
}
//////////////////////////////////////////////////////////////////////
/*! retrieve the id of a specified string
@param szKey the string value
@return the numeric id representing the string
*/
int CScriptObjectLanguage::GetStringID(const char *szKey)
{
int nRes;
if (m_pScriptThis->GetValue(szKey,nRes))
return (nRes);
return (-1);
}
int CScriptObjectLanguage::GetEnglish(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
char *szKey = 0;
pH->GetParam(1, szKey); // don't check for return - szKey still might be 0
if(!szKey)
return pH->EndFunctionNull();
wstring weng;
m_pMgr->Localize(szKey, weng, 1);
std::vector<char> tmp;
tmp.resize(weng.size()+1);
sprintf (&tmp[0], "%S", weng.c_str());
return pH->EndFunction(&tmp[0]);
}
//////////////////////////////////////////////////////////////////////
/*! load a string table from disk and add all contents into the global string table
@param sString the file path of the string table
@return !=nil(succeded) nil(failed)
*/
int CScriptObjectLanguage::LoadStringTable(IFunctionHandler *pH)
{
if (pH->GetParamCount()!=1)
{
m_pScriptSystem->RaiseError("Language::LoadStringTable wrong number of parameters");
pH->EndFunctionNull();
}
const char *sString;
pH->GetParam(1, sString); // don't check for return - sString still might be 0
if(!sString)
return pH->EndFunctionNull();
return pH->EndFunction(m_pMgr->LoadStringTable(sString));
}

View File

@@ -0,0 +1,60 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectLanguage.h: interface for the CScriptObjectLanguage class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTLANGUAGE_H__A399B2EE_7076_4B23_9A77_0A2F7FEFFEAB__INCLUDED_)
#define AFX_SCRIPTOBJECTLANGUAGE_H__A399B2EE_7076_4B23_9A77_0A2F7FEFFEAB__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <_ScriptableEx.h>
class CStringTableMgr;
/*! This class implements all language-related script-functions.
REMARKS:
After initialization of the script-object it will be globally accessable through scripts using the namespace "Language".
Example:
Language.LoadStringTable("script_table.xml");
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectLanguage :
public _ScriptableEx<CScriptObjectLanguage>
{
public:
//! constructor
CScriptObjectLanguage();
//! destructor
virtual ~CScriptObjectLanguage();
//!
void Init(IScriptSystem *pScriptSystem,CStringTableMgr *pMgr);
//!
void AddString(const char *s,int nID);
//!
// string GetEnglish( const char *inszKey ) const;
//! return -1 if string not found
int GetStringID(const char *szKey);
//!
int LoadStringTable(IFunctionHandler *pH);
//!
int GetEnglish(IFunctionHandler *pH);
//!
static void InitializeTemplate(IScriptSystem *pSS);
private:
CStringTableMgr * m_pMgr; //!<
};
#endif // !defined(AFX_SCRIPTOBJECTLANGUAGE_H__A399B2EE_7076_4B23_9A77_0A2F7FEFFEAB__INCLUDED_)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,224 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectPlayer.h: interface for the CScriptObjectPlayer class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTPLAYER_H__29A77DC8_C5A4_487C_943B_FF56EA8E01EE__INCLUDED_)
#define AFX_SCRIPTOBJECTPLAYER_H__29A77DC8_C5A4_487C_943B_FF56EA8E01EE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
#include <ScriptObjectVector.h>
class CPlayer;
/*! In this class are all player-related script-functions implemented.
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
enum SOP_MEMBER_LUA_TABLES {
SOP_MEMBER_TV_HELPER,
SOP_MEMBER_SHAKE_AXIS,
SOP_MEMBER_LAST
};
class CScriptObjectPlayer :
public _ScriptableEx<CScriptObjectPlayer>,
public IScriptObjectSink
{
public:
CScriptObjectPlayer();
virtual ~CScriptObjectPlayer();
bool Create(IScriptSystem *pScriptSystem);
void SetPlayer(CPlayer *pPlayer);
//IScriptObjectSink
void OnRelease()
{
m_pScriptThis=NULL;
delete this;
}
static void InitializeTemplate(IScriptSystem *pSS);
static void ReleaseTemplate();
public:
int RedirectInputTo(IFunctionHandler *pH);
int DeselectWeapon(IFunctionHandler *pH);
CPlayer * GetPlayer();
int GetWeaponInfo(IFunctionHandler *pH);
int GetWeaponsSlots(IFunctionHandler *pH);
int CalculateAccuracyFactor(IFunctionHandler *pH);
int WaitForFireRelease(IFunctionHandler *pH);
//int SetWeaponInfo(IFunctionHandler *pH);
int SetCurrWeapon(IFunctionHandler *pH);
int SetSwayAmp(IFunctionHandler *pH);
int SetSwayFreq(IFunctionHandler *pH);
int GetCurrWeapon(IFunctionHandler *pH);
int GetViewIntersection(IFunctionHandler *pH);
int SetGravity(IFunctionHandler *pH);
int SetAngleLimit(IFunctionHandler *pH);
int SetAngleLimitH(IFunctionHandler *pH);
int SetAngleLimitV(IFunctionHandler *pH);
int GetAngleLimitH(IFunctionHandler *pH);
int GetAngleLimitV(IFunctionHandler *pH);
int SetAngleLimitBase(IFunctionHandler *pH);
int SetMinAngleLimitV(IFunctionHandler *pH);
int SetMaxAngleLimitV(IFunctionHandler *pH);
int EnableAngleLimitV(IFunctionHandler *pH);
int SetMinAngleLimitH(IFunctionHandler *pH);
int SetMaxAngleLimitH(IFunctionHandler *pH);
int EnableAngleLimitH(IFunctionHandler *pH);
int SetName(IFunctionHandler *pH);
int GetName(IFunctionHandler *pH);
int MakeWeaponAvailable(IFunctionHandler *pH);
int InitWeapons(IFunctionHandler *pH);
int GetCurrWeaponId(IFunctionHandler *pH);
int CalcDmgShakeAxis(IFunctionHandler *pH);
int ShakeCamera(IFunctionHandler *pH);
int SetCameraOffset(IFunctionHandler *pH);
int GetCameraOffset(IFunctionHandler *pH);
// int Die(IFunctionHandler *pH);
int StartDie(IFunctionHandler *pH);
int HasCollided(IFunctionHandler *pH);
int SetDimNormal(IFunctionHandler *pH);
int SetDimCrouch(IFunctionHandler *pH);
int SetDimProne(IFunctionHandler *pH);
int GetBoneHitZone(IFunctionHandler *pH);
int GetArmDamage(IFunctionHandler *pH);
int GetLegDamage(IFunctionHandler *pH);
int SetMoveParams(IFunctionHandler *pH);
int HolsterGun(IFunctionHandler *pH);
int HoldGun(IFunctionHandler *pH);
int GetColor(IFunctionHandler *pH);
/*
int AllignOnSurface(IFunctionHandler *pH);
int SetAngleLimitBaseOnEnviroment(IFunctionHandler *pH);
int SetAngleLimitBaseOnVertical(IFunctionHandler *pH);
int SetRunSpeed(IFunctionHandler *pH);
int SetWalkSpeed(IFunctionHandler *pH);
int SetCrouchSpeed(IFunctionHandler *pH);
int SetProneSpeed(IFunctionHandler *pH);
int SetJumpForce(IFunctionHandler *pH);
int SetLean(IFunctionHandler *pH);
int SetCameraBob(IFunctionHandler *pH);
int SetWeaponBob(IFunctionHandler *pH);*/
int SetDynamicsProperties(IFunctionHandler *pH);
int SetSmoothInput(IFunctionHandler *pH);
int GetTreadedOnMaterial(IFunctionHandler *pH);
int GetTouchedMaterial(IFunctionHandler *pH);
int GetTPVHelper(IFunctionHandler *pH);
int GetHelperPos(IFunctionHandler *pH);
int GetTargetScreenPos(IFunctionHandler *pH);
int GetTargetTime(IFunctionHandler *pH);
int ShakeCameraL(IFunctionHandler *pH);
int SelectFirstWeapon(IFunctionHandler *pH);
int GetCurVehicle(IFunctionHandler *pH);
// int SetAnimationRefSpeed(IFunctionHandler *pH);
int SetAnimationRefSpeedRun(IFunctionHandler *pH);
int SetAnimationRefSpeedWalkRelaxed(IFunctionHandler *pH);
int SetAnimationRefSpeedWalk(IFunctionHandler *pH);
int SetAnimationRefSpeedXRun(IFunctionHandler *pH);
int SetAnimationRefSpeedXWalk(IFunctionHandler *pH);
int SetAnimationRefSpeedCrouch(IFunctionHandler *pH);
int DrawThirdPersonWeapon(IFunctionHandler *pH);
int SetDimOverride(IFunctionHandler *pH);
int CounterAdd(IFunctionHandler *pH);
int CounterIncrement(IFunctionHandler *pH);
int CounterGetValue(IFunctionHandler *pH);
int CounterSetValue(IFunctionHandler *pH);
int CounterSetEvent(IFunctionHandler *pH);
int GetCharacterAngles(IFunctionHandler *pH);
int SwitchFlashLight(IFunctionHandler *pH);
int GiveFlashLight(IFunctionHandler *pH);
int GiveBinoculars(IFunctionHandler *pH);
int IsSwimming(IFunctionHandler *pH);
int GetBlindScreenPos(IFunctionHandler *pH);
//
//-----------------------------------------------------------------------------------------------
// for debug/test purposes
int StartFire(IFunctionHandler *pH);
int ClearFire(IFunctionHandler *pH);
int PlaySound(IFunctionHandler *pH);
int GetFirePosAngles(IFunctionHandler *pH);
int SetPivot(IFunctionHandler *pH);
int SetHeatVisionValues(IFunctionHandler *pH);
int SetBlendTime(IFunctionHandler *pH); // sets blend time for particular animation
// makes some player stats persistent
int SavePlayerElements(IFunctionHandler *pH);
int LoadPlayerElements(IFunctionHandler *pH);
private:
CPlayer *m_pPlayer;
static IScriptObject *m_pTempObj;
static IScriptObject *m_pTempAng;
static IScriptObject *m_pWeaponSlots;
static IScriptObject *m_pTempBloodObj;
static IScriptObject *m_pBlindScreenPos;
CScriptObjectVector m_pCameraOffset;
CScriptObjectVector m_pGetColor;
_SmartScriptObject m_pWeaponInfo;
// member script objects (preallocated)
static IScriptObject* m_memberSO[SOP_MEMBER_LAST];
void SetMemberVector( SOP_MEMBER_LUA_TABLES member,const Vec3 &vec );
int m_LastTouchedMaterialID;
float m_fSpeedRun;
float m_fSpeedWalk;
float m_fSpeedCrouch;
float m_fSpeedProne;
public:
int SelectNextWeapon(IFunctionHandler * pH);
int SetAISpeedMult(IFunctionHandler *pH);
int InitDynamicLight(IFunctionHandler *pH);
int InitStaminaTable(IFunctionHandler *pH);
int GetProjectedBloodPos(IFunctionHandler *pH);
IEntityRender * GetIEntityRender(const struct pe_params_foreign_data & fd);
int UseLadder(IFunctionHandler *pH);
int GetCrosshairState(IFunctionHandler *pH);
int ResetCamera(IFunctionHandler *pH);
int ResetRotateHead(IFunctionHandler *pH);
int CanStand(IFunctionHandler *pH);
};
#endif // !defined(AFX_SCRIPTOBJECTPLAYER_H__29A77DC8_C5A4_487C_943B_FF56EA8E01EE__INCLUDED_)

View File

@@ -0,0 +1,182 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectRender.cpp
//
// Description:
// ScriptObjectRender.cpp: implementation of the CScriptObjectRender class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "scriptobjectrenderer.h"
#include "IRenderer.h"
#define REG_FUNC(_class,_func) _class::RegisterFunction(pSS,#_func,&_class::_func);
_DECLARE_SCRIPTABLEEX(CScriptObjectRenderer)
CScriptObjectRenderer::CScriptObjectRenderer(void)
{
}
CScriptObjectRenderer::~CScriptObjectRenderer(void)
{
}
IScriptObject *CScriptObjectRenderer::Create(IScriptSystem *pSS,IRenderer *pRen)
{
Init(pSS,this);
//m_pScriptThis->RegisterParent(this);
IScriptObject *pHolder=pSS->CreateObject();
//pHolder->SetValue("0",pSS->CreateUserData((int)this,USER_DATA_SCRIPTOBJRENDERER));
//pHolder->Delegate(m_pScriptThis);
m_pRenderer=pRen;
return m_pScriptThis;
}
void CScriptObjectRenderer::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectRenderer>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectRenderer,Reset);
REG_FUNC(CScriptObjectRenderer,PushQuad);
REG_FUNC(CScriptObjectRenderer,Draw);
}
int CScriptObjectRenderer::Reset(IFunctionHandler *pH)
{
m_vBuffer.resize(0);
m_vIdxBuf.resize(0);
return pH->EndFunction();
}
int CScriptObjectRenderer::PushQuad(IFunctionHandler *pH)
{
int params=pH->GetParamCount();
if(params<5)
{
m_pScriptSystem->RaiseError("CScriptObjectRenderer::PushQuad wrong number of params");
return pH->EndFunction();
}
float x,y,w,h,r=1,g=1,b=1,a=1,u0,v0,u1,v1;
_SmartScriptObject pTI(m_pScriptSystem,true);
pH->GetParam(1,x);
pH->GetParam(2,y);
pH->GetParam(3,w);
pH->GetParam(4,h);
if(!pH->GetParam(5,pTI))
{
m_pScriptSystem->RaiseError("CScriptObjectRenderer::PushQuad Invalid texinfo");
return pH->EndFunction();
}
pTI->GetAt(1,u0);
pTI->GetAt(2,v0);
pTI->GetAt(3,u1);
pTI->GetAt(4,v1);
if(params>5)
{
if(m_pRenderer->GetFeatures() & RFT_RGBA)
{
pH->GetParam(6,r);
pH->GetParam(7,g);
pH->GetParam(8,b);
pH->GetParam(9,a);
}
else
{
pH->GetParam(6,b);
pH->GetParam(7,g);
pH->GetParam(8,r);
pH->GetParam(9,a);
}
}
_Vtx vtx[4];
unsigned short base=m_vBuffer.size();
vtx[0].x=x;
vtx[0].y=y;
vtx[0].z=1.0f;
vtx[0].u=u0;
vtx[0].v=v0;
vtx[1].x=x+w;
vtx[1].y=y;
vtx[1].z=1.0f;
vtx[1].u=u1;
vtx[1].v=v0;
vtx[2].x=x+w;
vtx[2].y=y+h;
vtx[2].z=1.0f;
vtx[2].u=u1;
vtx[2].v=v1;
vtx[3].x=x;
vtx[3].y=y+h;
vtx[3].z=1.0f;
vtx[3].u=u0;
vtx[3].v=v1;
assert (r<=1 && g<=1 && b<=1 && a<=1);
for(int i=0;i<4;i++)
{
vtx[i].cc[0]=(unsigned char)(r*255.0f);
vtx[i].cc[1]=(unsigned char)(g*255.0f);
vtx[i].cc[2]=(unsigned char)(b*255.0f);
vtx[i].cc[3]=(unsigned char)(a*255.0f);
m_vBuffer.push_back(vtx[i]);
}
m_vIdxBuf.push_back(base);
m_vIdxBuf.push_back(base+1);
m_vIdxBuf.push_back(base+3);
m_vIdxBuf.push_back(base+1);
m_vIdxBuf.push_back(base+2);
m_vIdxBuf.push_back(base+3);
return pH->EndFunction();
}
int CScriptObjectRenderer::Draw(IFunctionHandler *pH)
{
if (m_vBuffer.size() > 0 && m_vIdxBuf.size() > 0)
{
USER_DATA tid;
int cookie;
if(pH->GetParamCount()<1)
{
m_pScriptSystem->RaiseError("CScriptObjectRenderer::Draw wrong number of params");
return pH->EndFunction();
}
if((!pH->GetParamUDVal(1,tid,cookie)) || (!(cookie==USER_DATA_TEXTURE)))
{
m_pScriptSystem->RaiseError("CScriptObjectRenderer::Draw invalid texture");
return pH->EndFunction();
}
//m_pRenderer->ResetToDefault();
m_pRenderer->Set2DMode(true,800,600);
m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST);
m_pRenderer->SetTexture(tid);
m_pRenderer->SetColorOp(eCO_MODULATE, eCO_MODULATE, DEF_TEXARG0, DEF_TEXARG0);
m_pRenderer->SetCullMode(R_CULL_DISABLE);
m_pRenderer->DrawDynVB((struct_VERTEX_FORMAT_P3F_COL4UB_TEX2F *)&m_vBuffer[0], &m_vIdxBuf[0], m_vBuffer.size(), m_vIdxBuf.size(), R_PRIMV_TRIANGLES);
m_pRenderer->Set2DMode(false,0,0);
}
m_vBuffer.resize(0);
m_vIdxBuf.resize(0);
return pH->EndFunction();
}

View File

@@ -0,0 +1,54 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SCRIPT_OBJECT_RENDERER_H_
#define _SCRIPT_OBJECT_RENDERER_H_
#include <vector>
#include <IRenderer.h>
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
struct IRenderer;
class CVertexBuffer;
#define USER_DATA_SCRIPTOBJRENDERER 0x100
typedef union tag_Clr
{
unsigned int c;
unsigned char cc[4];
}_Clr;
typedef struct tag_Vtx
{
float x,y,z;
unsigned char cc[4];
float u,v;
}_Vtx;
typedef std::vector<_Vtx> _VtxVec;
typedef std::vector<unsigned short> _IdxBuf;
class CScriptObjectRenderer :
public _ScriptableEx<CScriptObjectRenderer>
{
public:
CScriptObjectRenderer(void);
virtual ~CScriptObjectRenderer(void);
static void InitializeTemplate(IScriptSystem *pSS);
IScriptObject *Create(IScriptSystem *pSS,IRenderer *pRen);
int Reset(IFunctionHandler *pH);
int PushQuad(IFunctionHandler *pH);
int Draw(IFunctionHandler *pH);
private:
_VtxVec m_vBuffer;
_IdxBuf m_vIdxBuf;
IRenderer *m_pRenderer;
};
#endif

View File

@@ -0,0 +1,873 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "IXSystem.h"
#include "ScriptObjectServer.h"
#include "ScriptObjectVector.h"
//#include "TeamMgr.h"
_DECLARE_SCRIPTABLEEX(CScriptObjectServer)
CScriptObjectServer::CScriptObjectServer()
{
m_pServer=NULL;
m_pSlotMap=NULL;
}
CScriptObjectServer::~CScriptObjectServer()
{
if(m_pSlotMap)
m_pSlotMap->Release();
m_pSlotMap=NULL;
}
//! create the object into the LUA VM
bool CScriptObjectServer::Create(IScriptSystem *pScriptSystem,IXSystem *pXSystem,CXGame *pGame)
{
m_pXSystem=pXSystem;
m_pGame=pGame;
InitGlobal(pScriptSystem,"Server",this);
m_pSlotMap=pScriptSystem->CreateObject();
return true;
}
void CScriptObjectServer::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectServer>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectServer,Unban);
REG_FUNC(CScriptObjectServer,ListBans);
REG_FUNC(CScriptObjectServer,GetServerSlotMap);
// REG_FUNC(CScriptObjectServer,IsValidServerSlotId);
REG_FUNC(CScriptObjectServer,GetServerSlotByEntityId);
REG_FUNC(CScriptObjectServer,GetServerSlotBySSId);
// REG_FUNC(CScriptObjectServer,MultiCastObituary);
REG_FUNC(CScriptObjectServer,GetNumPlayers);
REG_FUNC(CScriptObjectServer,BroadcastText);
REG_FUNC(CScriptObjectServer,BroadcastCommand);
REG_FUNC(CScriptObjectServer,SpawnEntity);
REG_FUNC(CScriptObjectServer,RemoveEntity);
REG_FUNC(CScriptObjectServer,AddTeam);
REG_FUNC(CScriptObjectServer,RemoveTeam);
REG_FUNC(CScriptObjectServer,AddToTeam);
REG_FUNC(CScriptObjectServer,RemoveFromTeam);
REG_FUNC(CScriptObjectServer,SetTeamScoreByEntity);
REG_FUNC(CScriptObjectServer,GetTeamMemberCount);
REG_FUNC(CScriptObjectServer,SetTeamScore);
REG_FUNC(CScriptObjectServer,SetTeamFlags);
REG_FUNC(CScriptObjectServer,GetRespawnPoint);
REG_FUNC(CScriptObjectServer,GetRandomRespawnPoint);
REG_FUNC(CScriptObjectServer,GetNextRespawnPoint);
REG_FUNC(CScriptObjectServer,GetPrevRespawnPoint);
REG_FUNC(CScriptObjectServer,GetFirstRespawnPoint);
REG_FUNC(CScriptObjectServer,GetName);
REG_FUNC(CScriptObjectServer,DebugTest);
}
/////////////////////////////////////////////////////////
/*! return the number of players
@return the number of players
*/
int CScriptObjectServer::GetNumPlayers(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0)
return pH->EndFunction(m_pServer->GetNumPlayers());
}
/////////////////////////////////////////////////////////
//! return the serverslot that map on the given id
int CScriptObjectServer::GetServerSlotBySSId(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1)
int nId;
if(!pH->GetParam(1,nId))
return pH->EndFunction(false);
CXServer::XSlotMap::iterator itor;
itor=m_pServer->GetSlotsMap().find(nId);
if(itor!=m_pServer->GetSlotsMap().end())
return pH->EndFunction(itor->second->GetScriptObject());
return pH->EndFunction(false);
}
int CScriptObjectServer::Unban(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
if (pH->GetParamType(1) != svtNumber)
{
return pH->EndFunctionNull();
}
int iBanNumber = -1;
pH->GetParam(1, iBanNumber);
if (iBanNumber >= 0)
{
if (iBanNumber < m_pServer->m_vBannedIDList.size())
{
BannedID Banned = m_pServer->m_vBannedIDList[iBanNumber];
m_pServer->UnbanID(Banned);
GetISystem()->GetILog()->Log("\001removed ban on player: %s", Banned.szName.c_str());
}
else if (iBanNumber < m_pServer->m_vBannedIDList.size() + m_pServer->m_vBannedIPList.size())
{
unsigned int Banned = m_pServer->m_vBannedIPList[iBanNumber-m_pServer->m_vBannedIDList.size()];
m_pServer->UnbanIP(Banned);
CIPAddress ip;
ip.m_Address.ADDR = Banned;
GetISystem()->GetILog()->Log("\001removed ban on ip: %s", ip.GetAsString());
}
}
return pH->EndFunctionNull();
}
int CScriptObjectServer::ListBans(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
if (!m_pServer)
{
return pH->EndFunctionNull();
}
IConsole *pConsole = GetISystem()->GetIConsole();
pConsole->PrintLine("\t# name/ip");
int i = 0;
for (BannedIDList::iterator it = m_pServer->m_vBannedIDList.begin(); it != m_pServer->m_vBannedIDList.end(); ++it)
{
char szLine[512] = {0};
sprintf(szLine, "\t%d %s", i, it->szName.c_str());
pConsole->PrintLine(szLine);
++i;
}
for (BannedIPList::iterator it = m_pServer->m_vBannedIPList.begin(); it != m_pServer->m_vBannedIPList.end(); ++it)
{
char szLine[512] = {0};
CIPAddress ip;
ip.m_Address.ADDR = *it;
sprintf(szLine, "\t%d %s", i, ip.GetAsString());
pConsole->PrintLine(szLine);
++i;
}
return pH->EndFunctionNull();
}
/////////////////////////////////////////////////////////
/*! return a script table filled with the couple [serverslot id/serverslot script object]
@return the table containing all serverslot objects
*/
int CScriptObjectServer::GetServerSlotMap(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0)
CXServer::XSlotMap::iterator itor=m_pServer->GetSlotsMap().begin();
CXServer::XSlotMap::iterator end=m_pServer->GetSlotsMap().end();
m_pSlotMap->Clear();
while(itor!=end)
{
m_pSlotMap->SetAt(itor->second->GetID(),itor->second->GetScriptObject());
++itor;
}
return pH->EndFunction(m_pSlotMap);
}
/////////////////////////////////////////////////////////
// return if a creatin id is mapped to avalid serverslot
// @param nId server slot id
// @return !=nil(true) nil(false)
/*
int CScriptObjectServer::IsValidServerSlotId(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1)
int nId;
if(!pH->GetParam(1,nId))
return pH->EndFunction(false);
CXServer::XSlotMap::iterator itor;
itor=m_pServer->GetSlotsMap().find(nId);
bool bRet=(itor!=m_pServer->GetSlotsMap().end());
return pH->EndFunction(bRet);
}
*/
/////////////////////////////////////////////////////////
/*! retreive the serverslot passing the entity that identify his player
@param nEntityId id of the entity
*/
int CScriptObjectServer::GetServerSlotByEntityId(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1)
int val;
if(!pH->GetParam(1, val))
return pH->EndFunction(false);
EntityId nEntityId = val;
CXServerSlot *pRet=m_pServer->GetServerSlotByEntityId(nEntityId);
if(pRet)
return pH->EndFunction(pRet->GetScriptObject());
return pH->EndFunction(false); // not found
}
/////////////////////////////////////////////////////////
/*
int CScriptObjectServer::MultiCastObituary(IFunctionHandler *pH)
{
CHECK_PARAMETERS(3);
int targid, attid, situation;
pH->GetParam(1, targid);
pH->GetParam(2, attid);
pH->GetParam(3, situation);
CStream stm;
stm.Write((EntityId)targid);
stm.Write((EntityId)attid);
stm.Write((char)situation);
m_pServer->BroadcastReliable(XSERVERMSG_OBITUARY, stm,true);
return pH->EndFunction();
}
*/
/////////////////////////////////////////////////////////
/*! Send text to all connected clients
@param sText the text that must be sent
*/
int CScriptObjectServer::BroadcastText(IFunctionHandler *pH)
{
const char *sText=NULL;
if(pH->GetParam(1,sText) && m_pServer && sText)
{
float fLifeTime = DEFAULT_TEXT_LIFETIME;
pH->GetParam(2, fLifeTime);
m_pServer->BroadcastText(sText, fLifeTime);
}
return pH->EndFunction();
}
/////////////////////////////////////////////////////////
/*! Destroys an entity
@param A reference to the entity that is to be destroyed
If the entity reference is invalid, the call is ignored
@see RemoveEntity
*/
int CScriptObjectServer::RemoveEntity(IFunctionHandler *pH)
{
// CHECK_PARAMETERS(1);
ASSERT(pH && (pH->GetParamCount() == 1 || pH->GetParamCount() == 2));
int iEntity=0;
bool bRemoveNow=false;
//if(pH->GetParam(1, iEntity))
pH->GetParam(1, iEntity);
IEntity* pEntity=m_pXSystem->GetEntity(iEntity);
if(!pEntity || pEntity->IsGarbage())
return pH->EndFunction();
if(pH->GetParamCount() == 2)
bRemoveNow = true;
if (iEntity)
m_pXSystem->RemoveEntity((EntityId) iEntity, bRemoveNow);
return pH->EndFunction();
}
/////////////////////////////////////////////////////////
/*! Creates an entity
@param The class id or class name of the entity that is to be created
@param Optional world position of where the entity will be created
@return If successful it returns a reference to the new entity that is created
Otherwise it returns NULL
@see RemoveEntity
*/
int CScriptObjectServer::SpawnEntity(IFunctionHandler *pH)
{
// Ensure that there is only one parameter
// CHECK_PARAMETERS(1);
//static EntityId nEntityID=20000;
// Added optional position parameter so that position is valid during the objects OnInit()
ASSERT(pH && (pH->GetParamCount() == 1 || pH->GetParamCount() == 2));
int iEntityClassID;
EntityClassId ClassId;
const char* sEntityClassName;
const char *sName="";
const char *sModel="";
EntityClass *pClass;
CEntityDesc ed;
Vec3 pos(0,0,0);
Vec3 angles(0,0,0);
int requestedid=0;
_SmartScriptObject pED(m_pScriptSystem,true);
CScriptObjectVector o(m_pScriptSystem,true);
_SmartScriptObject pProperties(m_pScriptSystem,true);
bool bproperties=false;
//if the first parameter is a table(is the entity description)
if(pH->GetParam(1, pED))
{
if(!pED->GetValue("classid",iEntityClassID))
return pH->EndFunctionNull();
ClassId=(EntityClassId)iEntityClassID;
pClass=m_pGame->GetClassRegistry()->GetByClassId(ClassId);
if(!pClass)
return pH->EndFunctionNull();
pED->GetValue("name",sName);
pED->GetValue("model",sModel);
if(pED->GetValue("properties",pProperties))
{
bproperties=true;
}
if(pED->GetValue("pos",o))
{
pos=o.Get();
}
if(pED->GetValue("angles",o))
{
angles=o.Get();
}
pED->GetValue("id",requestedid);
// color used for team identification
CScriptObjectColor oCol(m_pScriptSystem,true);
if (pED->GetValue( "color",oCol ))
ed.vColor = oCol.Get();
}
else
{
// First try reading the parameter as class ID (int)
if(!pH->GetParam(1, iEntityClassID))
{
// Parameter is not an int so now try reading as a string
if(!pH->GetParam(1, sEntityClassName))
// Parameter appears to be invalid so bail
return pH->EndFunctionNull();
// Convert string to class id
pClass=m_pGame->GetClassRegistry()->GetByClass(sEntityClassName);
if(!pClass)
{
m_pGame->GetSystem()->GetILog()->LogError("Server:SpawnEntity failed, class name '%s' not recognized", sEntityClassName);
return pH->EndFunctionNull();
}
ClassId = pClass->ClassId;
}
else
{
ClassId=(EntityClassId)iEntityClassID;
pClass=m_pGame->GetClassRegistry()->GetByClassId(ClassId);
if(!pClass)
return pH->EndFunctionNull();
}
// We now have a valid class ID
//Vec3 StartPosition(0.0, 0.0, 0.0);
if(pH->GetParamCount() == 2)
{
CScriptObjectVector oVec(m_pScriptSystem,true);
// Read the optional position parameter
pH->GetParam(2,*oVec);
pos = oVec.Get();
}
}
ed.ClassId = ClassId;
ed.className = pClass->strClassName.c_str();
ed.pos = pos;
ed.angles=angles;
ed.name=sName;
ed.sModel=sModel;
ed.id=requestedid;
if(bproperties)
{
ed.pProperties=pProperties;
}
IEntity* pEntity;
ILog *pLog=m_pGame->GetSystem()->GetILog();
if (pLog->GetVerbosityLevel()>5)
{
// Timur, excessive logging.
//pLog->Log("Attempt to spawn entity classname=%s,name=%s,type=%d,id=%d (%.2f %.2f %.2f)",ed.className.c_str(),ed.name.c_str(),(int)ed.ClassId,ed.id,pos.x,pos.y,pos.z);
}
// Attempt to spawn the object using the class ID
if((pEntity = m_pXSystem->SpawnEntity(ed)) == NULL)
// Spawn failed
return pH->EndFunctionNull();
// Returns a pointer to the IScriptObject
return pH->EndFunction(pEntity->GetScriptObject());
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/*!add a team into the game
@param pszName name of the team
*/
int CScriptObjectServer::AddTeam(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *pszName;
pH->GetParam(1, pszName);
//m_pGame->GetTeamManager()->AddTeam(pszName);
m_pServer->AddTeam(pszName);
//m_pServer->m_pISystem->AddTeam(pszName,-1);
return pH->EndFunction();
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/*!remove a team from the game
@param pszName name of the team
*/
int CScriptObjectServer::RemoveTeam(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *pszName;
pH->GetParam(1, pszName);
//m_pGame->GetTeamManager()->RemoveTeam(m_pGame->GetTeamManager()->NameToId(pszName));
//int nTID=m_pServer->m_pISystem->GetTeamId(pszName);
m_pServer->RemoveTeam(pszName);
//m_pServer->m_pISystem->RemoveTeam(nTID);
return pH->EndFunction();
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/*!add an entity into a team
@param pszName name of the theam
@param id the entity's id
*/
int CScriptObjectServer::AddToTeam(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
const char *pszName;
int id=0;
if(pH->GetParam(1, pszName))
{
pH->GetParam(2, id);
int nTID=m_pServer->m_pISystem->GetEntityTeam(id);
if(nTID!=-1)
{
m_pServer->RemoveFromTeam(id);
}
// CTeamMgr *pTM=m_pGame->GetTeamManager();
// CTeam *pTeam=pTM->GetTeam(pTM->NameToId(pszName));
// if(pTeam)
// {
// pTeam->AddEntity(id);
// }
m_pServer->AddToTeam(pszName,id);
}
return pH->EndFunction();
}
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/*!remove an entity from a team
@param id the entity's id
*/
int CScriptObjectServer::RemoveFromTeam(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int id=0;
if(pH->GetParam(1, id))
{
//CTeamMgr *pTM=m_pGame->GetTeamManager();
//if(pTM)
//{
//CTeam *pTeam=pTM->GetEntityTeam(id);
//if(pTeam)
//{
//pTeam->RemoveEntity(id);
//}
//}
m_pServer->RemoveFromTeam(id);
}
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////
//void (return vector)
////////////////////////////////////////////////////////////////////
/*!return a respawn point from the respawn points specified in levedata.xml by a given name
@param name name of the respawn point
@return if succeded a table with the fields x,y,z containing the pos of the respawn point if failed return nil
*/
int CScriptObjectServer::GetRespawnPoint(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
char *name=NULL;
pH->GetParam(1,name);
if(!name)
return pH->EndFunction();
m_pGame->GetSystem()->GetILog()->Log("GetRespawnPoint '%s'",name?name:"<nil>");
ITagPoint *tag = m_pServer->GetRespawnPoint(name);
if(tag != NULL)
{
_SmartScriptObject pTagPoint(m_pScriptSystem);
MakeTagScriptObject(tag, pTagPoint);
return pH->EndFunction(*pTagPoint);
}
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////
//void (return vector)
////////////////////////////////////////////////////////////////////
/*!return a respawn first point from the respawn points specified in levedata.xml
@return a table with the fields x,y,z containing the pos of the respawn point
*/
int CScriptObjectServer::GetFirstRespawnPoint(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
ITagPoint *tag = m_pServer->GetFirstRespawnPoint();
if(tag != NULL)
{
_SmartScriptObject pTagPoint(m_pScriptSystem);
MakeTagScriptObject(tag, pTagPoint);
return pH->EndFunction(*pTagPoint);
}
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////
//void (return vector)
////////////////////////////////////////////////////////////////////
/*!return a respawn next point from the respawn points specified in levedata.xml
@return a table with the fields x,y,z containing the pos of the respawn point
*/
int CScriptObjectServer::GetNextRespawnPoint(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
ITagPoint *tag = m_pServer->GetNextRespawnPoint();
if(tag != NULL)
{
_SmartScriptObject pTagPoint(m_pScriptSystem);
MakeTagScriptObject(tag, pTagPoint);
return pH->EndFunction(*pTagPoint);
}
return pH->EndFunctionNull();
}
////////////////////////////////////////////////////////////////////
//void (return vector)
////////////////////////////////////////////////////////////////////
/*!return a respawn next point from the respawn points specified in levedata.xml
@return a table with the fields x,y,z containing the pos of the respawn point
*/
int CScriptObjectServer::GetPrevRespawnPoint(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
ITagPoint *tag = m_pServer->GetPrevRespawnPoint();
if(tag != NULL)
{
_SmartScriptObject pTagPoint(m_pScriptSystem);
MakeTagScriptObject(tag, pTagPoint);
return pH->EndFunction(*pTagPoint);
}
return pH->EndFunctionNull();
}
////////////////////////////////////////////////////////////////////
//void (return vector)
////////////////////////////////////////////////////////////////////
/*!return a respawn random point from the respawn points specified in levedata.xml
@return a table with the fields x,y,z containing the pos of the respawn point
*/
int CScriptObjectServer::GetRandomRespawnPoint(IFunctionHandler *pH)
{
const char *sFilter=NULL;
if(pH->GetParamCount())
pH->GetParam(1, sFilter);
// m_pGame->GetSystem()->GetILog()->Log("GetRandomRespawnPoint '%s'",sFilter?sFilter:"<nil>");
ITagPoint *tag = m_pServer->GetRandomRespawnPoint(sFilter);
if(tag != NULL)
{
_SmartScriptObject pTagPoint(m_pScriptSystem);
MakeTagScriptObject(tag, pTagPoint);
return pH->EndFunction(*pTagPoint);
}
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
/*! set the score of a team selecting the team by the entity id of an entity of the team
@param EntityId the entity's id
@param nScore the score that has to be set
*/
int CScriptObjectServer::SetTeamScoreByEntity(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int val;
if(!pH->GetParam(1, val))
return pH->EndFunction(false);
EntityId nEntityId = val;
int nScore;
pH->GetParam(2, nScore);
int nTID=m_pServer->m_pISystem->GetEntityTeam(nEntityId);
if(nTID!=-1)
m_pServer->m_pISystem->SetTeamScore(nTID,nScore);
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
/*!set the score of a team
@param teamname name of the team
@param score the score that has to be set
*/
int CScriptObjectServer::SetTeamScore(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
const char *team;
int score;
if(pH->GetParam(1,team))
{
pH->GetParam(2,score);
m_pServer->SetTeamScore(team,score);
}
return pH->EndFunctionNull();
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
/*!set the score of a team
@param teamname name of the team
@param flags the flags that has to be set
*/
int CScriptObjectServer::SetTeamFlags(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
const char *team;
int flags;
if(pH->GetParam(1,team))
{
pH->GetParam(2,flags);
m_pServer->SetTeamFlags(team,flags);
}
return pH->EndFunctionNull();
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
/*!return the number of members of a certain team
@param pszName name of the team
@return if succeded the number of members of the team if failed return nil
*/
int CScriptObjectServer::GetTeamMemberCount(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *pszName;
if(pH->GetParam(1, pszName))
{
int nTID=m_pServer->m_pISystem->GetTeamId(pszName);
if(nTID!=-1)
return pH->EndFunction(m_pServer->m_pISystem->GetTeamMembersCount(nTID));
// CTeamMgr *pTM=m_pGame->GetTeamManager();
// CTeam *pTeam=pTM->GetTeam(pTM->NameToId(pszName));
// if(pTeam)
// return pH->EndFunction(pTeam->GetMemberCount());
}
return pH->EndFunction(0);
}
int CScriptObjectServer::GetName(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction(m_pServer->GetName());
}
// should be removed in release - pure debugging purpose
int CScriptObjectServer::DebugTest(IFunctionHandler *pH)
{
/* deactivate because it can be used to hack
if(pH->GetParamCount()==0)
{
IEntitySystem *pEntitySystem=m_pGame->GetSystem()->GetIEntitySystem();
DWORD dwCount=pEntitySystem->GetNumEntities();
EntityId idChosen=(EntityId)(rand()%dwCount);
IEntity *pEnt=pEntitySystem->GetEntity(idChosen);
if(pEnt)
{
EntityClassId ClassId=pEnt->GetClassId();
EntityClass *pClass=m_pGame->GetClassRegistry()->GetByClassId(ClassId,false);
assert(pClass);
// debugging
m_pGame->GetSystem()->GetILog()->Log("Cheat protection: %d/%d %p class=%s\n",(int)idChosen,dwCount,pEnt,pClass->strClassName.c_str());
// if(pClass)
m_pServer->SendRequestScriptHash(idChosen,"","");
}
}
else
{
CHECK_PARAMETERS(2);
const char *path;
const char *key;
if(pH->GetParam(1,path))
if(pH->GetParam(2,key))
m_pServer->SendRequestScriptHash(0,path,key);
}
*/
return pH->EndFunctionNull();
}
int CScriptObjectServer::BroadcastCommand(IFunctionHandler *pH)
{
if(pH->GetParamCount()==1)
{
const char *cmd;
if(pH->GetParam(1,cmd))
{
m_pServer->BroadcastCommand(cmd);
}
}
else
{
CHECK_PARAMETERS(5);
const char *sString;
Vec3d vPos,vNormal;
int Id;
int iUserByte;
if(!pH->GetParam(1,sString))
return pH->EndFunction();
{
_SmartScriptObject tpos(m_pScriptSystem, true);
_VERIFY(pH->GetParam(2, tpos));
float x,y,z;
_VERIFY(tpos->GetValue("x", x));
_VERIFY(tpos->GetValue("y", y));
_VERIFY(tpos->GetValue("z", z));
vPos=Vec3d(x,y,z);
// m_pScriptSystem->PushFuncParam(vPos);
}
{
_SmartScriptObject tnormal(m_pScriptSystem, true);
_VERIFY(pH->GetParam(3, tnormal));
float x,y,z;
_VERIFY(tnormal->GetValue("x", x));
_VERIFY(tnormal->GetValue("y", y));
_VERIFY(tnormal->GetValue("z", z));
vNormal=Vec3d(x,y,z);
// m_pScriptSystem->PushFuncParam(vNormal);
}
if(!pH->GetParam(4,Id))
return pH->EndFunction();
if(!pH->GetParam(5,iUserByte))
return pH->EndFunction();
m_pServer->BroadcastCommand(sString,vPos,vNormal,(EntityId)Id,(unsigned char)iUserByte);
}
return pH->EndFunction();
}
void CScriptObjectServer::MakeTagScriptObject(ITagPoint* pInTagPoint, _SmartScriptObject& rOut)
{
Vec3 spawnpt, spawnangles;
pInTagPoint->GetPos(spawnpt);
pInTagPoint->GetAngles(spawnangles);
char* spawnname = pInTagPoint->GetName();
rOut->SetValue("x",spawnpt.x);
rOut->SetValue("y",spawnpt.y);
rOut->SetValue("z",spawnpt.z);
rOut->SetValue("xA",spawnangles.x);
rOut->SetValue("yA",spawnangles.y);
rOut->SetValue("zA",spawnangles.z);
rOut->SetValue("name",spawnname);
}

View File

@@ -0,0 +1,76 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SCRIPTOBJECTSERVER_H_
#define _SCRIPTOBJECTSERVER_H_
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CXServer;
/*! This class implements script-functions for exposing the server functionalities
REMARKS:
After initialization of the script-object it will be globally accessable through scripts using the namespace "Server".
This object isn't instantiated when the client is connected to a remote server
Example:
Server.SpawnEntity("Rocket");
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectServer :
public _ScriptableEx<CScriptObjectServer>
{
public:
CScriptObjectServer();
virtual ~CScriptObjectServer();
bool Create(IScriptSystem *pScriptSystem,IXSystem *pCSystem,CXGame *pGame);
void SetServer(CXServer *pServer){m_pServer=pServer;}
int Unban(IFunctionHandler *pH);
int ListBans(IFunctionHandler *pH);
int GetServerSlotBySSId(IFunctionHandler *pH);
int GetServerSlotByEntityId(IFunctionHandler *pH);
int GetServerSlotMap(IFunctionHandler *pH);
// int IsValidServerSlotId(IFunctionHandler *pH);
// int MultiCastObituary(IFunctionHandler *pH);
int GetNumPlayers(IFunctionHandler *pH);
int BroadcastText(IFunctionHandler *pH);
int SpawnEntity(IFunctionHandler *pH);
int RemoveEntity(IFunctionHandler *pH);
int AddTeam(IFunctionHandler *pH);
int RemoveTeam(IFunctionHandler *pH);
int AddToTeam(IFunctionHandler *pH);
int RemoveFromTeam(IFunctionHandler *pH);
int SetTeamScoreByEntity(IFunctionHandler *pH);
int SetTeamScore(IFunctionHandler *pH);
int GetTeamMemberCount(IFunctionHandler *pH);
int SetTeamFlags(IFunctionHandler *pH);
int GetRespawnPoint(IFunctionHandler *pH);
int GetFirstRespawnPoint(IFunctionHandler *pH);
int GetNextRespawnPoint(IFunctionHandler *pH);
int GetPrevRespawnPoint(IFunctionHandler *pH);
int GetRandomRespawnPoint(IFunctionHandler *pH);
int GetName(IFunctionHandler *pH);
int DebugTest(IFunctionHandler *pH);
int BroadcastCommand(IFunctionHandler *pH);
static void InitializeTemplate(IScriptSystem *pSS);
private:
static void MakeTagScriptObject(ITagPoint* pInTagPoint, _SmartScriptObject& rOut);
CXServer *m_pServer;
IScriptObject *m_pSlotMap;
IXSystem *m_pXSystem;
CXGame *m_pGame;
};
#endif //_SCRIPTOBJECTCLIENT_H_

View File

@@ -0,0 +1,307 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectServerSlot.cpp
//
// Description:
// ScriptObjectServerSlot.cpp: implementation of the ScriptObjectServerSlot class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "scriptobjectserverslot.h"
#include "XSystemBase.h"
#include "XServerslot.h"
_DECLARE_SCRIPTABLEEX(CScriptObjectServerSlot);
CScriptObjectServerSlot::CScriptObjectServerSlot(void)
{
m_pSS=NULL;
}
CScriptObjectServerSlot::~CScriptObjectServerSlot(void)
{
}
void CScriptObjectServerSlot::Create(IScriptSystem *pScriptSystem)
{
m_pSS=NULL;
Init(pScriptSystem,this);
}
void CScriptObjectServerSlot::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectServerSlot>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectServerSlot,BanByID);
REG_FUNC(CScriptObjectServerSlot,BanByIP);
REG_FUNC(CScriptObjectServerSlot,SetPlayerId);
REG_FUNC(CScriptObjectServerSlot,GetName);
REG_FUNC(CScriptObjectServerSlot,GetModel);
REG_FUNC(CScriptObjectServerSlot,GetColor);
REG_FUNC(CScriptObjectServerSlot,SetGameState);
REG_FUNC(CScriptObjectServerSlot,SendText);
REG_FUNC(CScriptObjectServerSlot,Ready);
REG_FUNC(CScriptObjectServerSlot,IsReady);
REG_FUNC(CScriptObjectServerSlot,IsContextReady);
REG_FUNC(CScriptObjectServerSlot,ResetPlayTime);
REG_FUNC(CScriptObjectServerSlot,SendCommand);
REG_FUNC(CScriptObjectServerSlot,Disconnect);
REG_FUNC(CScriptObjectServerSlot,GetId);
REG_FUNC(CScriptObjectServerSlot,GetPlayerId);
REG_FUNC(CScriptObjectServerSlot,GetPing);
REG_FUNC(CScriptObjectServerSlot,GetPlayTime);
}
int CScriptObjectServerSlot::BanByID(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
m_pSS->BanByID();
return pH->EndFunctionNull();
}
int CScriptObjectServerSlot::BanByIP(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
m_pSS->BanByIP();
return pH->EndFunctionNull();
}
/*!Send a string from the Serverslot(Server) to the Client (there OnServerCommand is invoked)
*/
int CScriptObjectServerSlot::SendCommand(IFunctionHandler *pH)
{
if(pH->GetParamCount()==1)
{
const char *sString;
if(pH->GetParam(1,sString))
m_pSS->SendCommand(sString);
}
else
{
if(pH->GetParamCount()!=5)
{
m_pScriptSystem->RaiseError( "CScriptObjectServerSlot::SendCommand : %d arguments passed, 1 or 4 expected)", pH->GetParamCount());
return pH->EndFunction();
}
const char *sString;
Vec3d vPos,vNormal;
int Id;
int iUserByte;
if(!pH->GetParam(1,sString))
return pH->EndFunction();
{
_SmartScriptObject tpos(m_pScriptSystem, true);
_VERIFY(pH->GetParam(2, tpos));
float x,y,z;
_VERIFY(tpos->GetValue("x", x));
_VERIFY(tpos->GetValue("y", y));
_VERIFY(tpos->GetValue("z", z));
vPos=Vec3d(x,y,z);
// m_pScriptSystem->PushFuncParam(vPos);
}
{
_SmartScriptObject tnormal(m_pScriptSystem, true);
_VERIFY(pH->GetParam(3, tnormal));
float x,y,z;
_VERIFY(tnormal->GetValue("x", x));
_VERIFY(tnormal->GetValue("y", y));
_VERIFY(tnormal->GetValue("z", z));
vNormal=Vec3d(x,y,z);
// m_pScriptSystem->PushFuncParam(vNormal);
}
if(!pH->GetParam(4,Id))
return pH->EndFunction();
if(!pH->GetParam(5,iUserByte))
return pH->EndFunction();
m_pSS->SendCommand(sString,vPos,vNormal,(EntityId)Id,(unsigned char)iUserByte);
}
return pH->EndFunction();
}
int CScriptObjectServerSlot::Disconnect(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
char *szCause = "";
pH->GetParam(1, szCause);
m_pSS->Disconnect(szCause);
return pH->EndFunctionNull();
}
/*!Set the state of the game
@param state state of the game (like intermission, prewar etc..)
@param time current time
*/
int CScriptObjectServerSlot::SetGameState(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int state, time;
pH->GetParam(1,state);
pH->GetParam(2,time);
if(m_pSS)
{
m_pSS->SetGameState(state, time);
m_pSS->m_bForceScoreBoard = state==CGS_INTERMISSION;
}
return pH->EndFunction();
}
/*!assign the player entity to the serverslot this entity from now will be considered
the player controlled by the remote client assigned to this server slot
@param nID the entity id
*/
int CScriptObjectServerSlot::SetPlayerId(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int nID;
if(pH->GetParam(1,nID) && m_pSS)
m_pSS->SetPlayerID(nID);
return pH->EndFunction();
}
/*!retrieve the id of the entity(player)
the player controlled by the remote client assigned to this server slot
@return the entity id
*/
int CScriptObjectServerSlot::GetPlayerId(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
int nID=0;
if(m_pSS)
nID=m_pSS->GetPlayerId();
return pH->EndFunction(nID);
}
/*!retrieve the name of the player assigned to this serverslot
@return the name of the player assigned to this serverslot
*/
int CScriptObjectServerSlot::GetName(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
const char *sName="";
if(m_pSS)
sName=m_pSS->GetName();
return pH->EndFunction(sName);
}
/*!retrieve the name of the player assigned to this serverslot
@return the name of the player assigned to this serverslot
*/
int CScriptObjectServerSlot::GetModel(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
const char *sModel="";
if(m_pSS)
sModel=m_pSS->GetModel();
return pH->EndFunction(sModel);
}
/*!retrieve the color of the player assigned to this serverslot
@return string which was specified on the client
*/
int CScriptObjectServerSlot::GetColor(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
const char *sColor="";
if(m_pSS)
sColor=m_pSS->GetColor();
return pH->EndFunction(sColor);
}
/*!send a tring of text to the client assigned to this serverslot
@param sText the text that as to be sent
*/
int CScriptObjectServerSlot::SendText(IFunctionHandler *pH)
{
//CHECK_PARAMETERS(1);
const char *sText=NULL;
float lifetime=DEFAULT_TEXT_LIFETIME;
if(pH->GetParamCount()){
if(pH->GetParam(1,sText) && m_pSS && sText)
{
if(pH->GetParamCount()>1){
pH->GetParam(2,lifetime);
}
m_pSS->SendText(sText,lifetime);
}
}
return pH->EndFunction();
}
/*!set the readyness state
@param bReady !=nil is true nil is false
*/
int CScriptObjectServerSlot::Ready(IFunctionHandler *pH)
{
bool bReady;
pH->GetParam(1,bReady);
m_pSS->m_bReady=bReady;
return pH->EndFunction();
}
/*!quesry the readyness state
*/
int CScriptObjectServerSlot::IsReady(IFunctionHandler *pH)
{
return pH->EndFunction(m_pSS->m_bReady);
}
int CScriptObjectServerSlot::IsContextReady(IFunctionHandler *pH)
{
return pH->EndFunction(m_pSS->IsContextReady());
}
int CScriptObjectServerSlot::ResetPlayTime(IFunctionHandler *pH)
{
m_pSS->ResetPlayTime();
return pH->EndFunction();
}
int CScriptObjectServerSlot::GetPing(IFunctionHandler *pH)
{
return pH->EndFunction((int)m_pSS->GetPing());
}
int CScriptObjectServerSlot::GetPlayTime(IFunctionHandler *pH)
{
return pH->EndFunction(m_pSS->GetPlayTime());
}
int CScriptObjectServerSlot::GetId(IFunctionHandler *pH)
{
return pH->EndFunction((int)m_pSS->GetID());
}

View File

@@ -0,0 +1,60 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SCRIPTOBJECTSERVERSLOT_H_
#define _SCRIPTOBJECTSERVERSLOT_H_
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CXServerSlot;
/*! This class implements script-functions for exposing the serverslots functionalities
REMARKS:
this object doesn't have a global mapping(is not present as global variable into the script state)
This object isn't instantiated when the client is connected to a remote server
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectServerSlot :
public _ScriptableEx<CScriptObjectServerSlot>
{
public:
//! constructor
CScriptObjectServerSlot();
//! destructor
virtual ~CScriptObjectServerSlot();
void Create(IScriptSystem *pScriptSystem);
void SetServerSlot(CXServerSlot *pSS){m_pSS=pSS;}
static void InitializeTemplate(IScriptSystem *pSS);
private:
int BanByID(IFunctionHandler *pH);
int BanByIP(IFunctionHandler *pH);
int SetPlayerId(IFunctionHandler *pH);
int GetPlayerId(IFunctionHandler *pH);
int GetName(IFunctionHandler *pH);
int GetModel(IFunctionHandler *pH);
int GetColor(IFunctionHandler *pH);
int SetGameState(IFunctionHandler *pH);
int SendText(IFunctionHandler *pH);
int Ready(IFunctionHandler *pH);
int IsReady(IFunctionHandler *pH);
int IsContextReady(IFunctionHandler *pH);
int ResetPlayTime(IFunctionHandler *pH);
int GetPlayTime(IFunctionHandler *pH);
int SendCommand(IFunctionHandler *pH);
int Disconnect(IFunctionHandler *pH);
int GetId(IFunctionHandler *pH);
int GetPing(IFunctionHandler *pH);
CXServerSlot * m_pSS; //!<
};
#endif

View File

@@ -0,0 +1,67 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectSpectator.cpp
//
// Description:
// ScriptObjectSpectator.cpp: implementation of the ScriptObjectSpectator class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "scriptobjectspectator.h"
#include "Spectator.h"
_DECLARE_SCRIPTABLEEX(CScriptObjectSpectator)
//////////////////////////////////////////////////////////////////////////
CScriptObjectSpectator::CScriptObjectSpectator(void)
{
}
//////////////////////////////////////////////////////////////////////////
CScriptObjectSpectator::~CScriptObjectSpectator(void)
{
}
//////////////////////////////////////////////////////////////////////////
void CScriptObjectSpectator::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectSpectator>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectSpectator,SetHost);
REG_FUNC(CScriptObjectSpectator,GetHost);
}
//////////////////////////////////////////////////////////////////////////
bool CScriptObjectSpectator::Create(IScriptSystem *pScriptSystem, CSpectator *pSpectator)
{
m_pSpectator=pSpectator;
Init(pScriptSystem, this);
m_pScriptThis->RegisterParent(this);
// Function-Registration
return true;
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectSpectator::SetHost(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int host=0;
if(pH->GetParam(1,host))
{
m_pSpectator->m_eiHost=host;
}
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectSpectator::GetHost(IFunctionHandler *pH)
{
return pH->EndFunction(m_pSpectator->m_eiHost);
}

View File

@@ -0,0 +1,41 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SCRIPTOBJECTSPECTATOR_H_
#define _SCRIPTOBJECTSPECTATOR_H_
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CSpectator;
/*! In this class are all spectator-related script-functions implemented.
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectSpectator :
public _ScriptableEx<CScriptObjectSpectator>,
public IScriptObjectSink
{
public:
CScriptObjectSpectator(void);
virtual ~CScriptObjectSpectator(void);
bool Create(IScriptSystem *pScriptSystem, CSpectator *pSpectator);
void OnRelease()
{
m_pScriptThis=NULL;
delete this;
}
static void InitializeTemplate(IScriptSystem *pSS);
int SetHost(IFunctionHandler *pH);
int GetHost(IFunctionHandler *pH);
private:
CSpectator *m_pSpectator;
};
#endif //_SCRIPTOBJECTSPECTATOR_H_

View File

@@ -0,0 +1,212 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// File: ScriptObjectStream.cpp
//
// Description:
// ScriptObjectStream.cpp: implementation of the CScriptObjectStream class.
//
// History:
// - created by Marco C.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ScriptObjectStream.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
_DECLARE_SCRIPTABLEEX(CScriptObjectStream)
CScriptObjectStream::CScriptObjectStream()
{
}
CScriptObjectStream::~CScriptObjectStream()
{
}
bool CScriptObjectStream::Create(IScriptSystem *pScriptSystem)
{
m_pStm=NULL;
Init(pScriptSystem,this);
return true;
}
void CScriptObjectStream::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectStream>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectStream,WriteInt);
REG_FUNC(CScriptObjectStream,WriteShort);
REG_FUNC(CScriptObjectStream,WriteByte);
REG_FUNC(CScriptObjectStream,WriteFloat);
REG_FUNC(CScriptObjectStream,WriteString);
REG_FUNC(CScriptObjectStream,WriteBool);
REG_FUNC(CScriptObjectStream,WriteNumberInBits);
REG_FUNC(CScriptObjectStream,ReadInt);
REG_FUNC(CScriptObjectStream,ReadShort);
REG_FUNC(CScriptObjectStream,ReadByte);
REG_FUNC(CScriptObjectStream,ReadFloat);
REG_FUNC(CScriptObjectStream,ReadString);
REG_FUNC(CScriptObjectStream,ReadBool);
REG_FUNC(CScriptObjectStream,ReadNumberInBits);
}
int CScriptObjectStream::WriteInt(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int n;
pH->GetParam(1,n);
m_pStm->Write(n);
return pH->EndFunction();
}
int CScriptObjectStream::WriteShort(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int n;
short int si;
pH->GetParam(1,n);
si=n;
m_pStm->Write(si);
return pH->EndFunction();
}
int CScriptObjectStream::WriteByte(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int n;
unsigned char uc;
pH->GetParam(1,n);
uc=n;
m_pStm->Write(uc);
return pH->EndFunction();
}
int CScriptObjectStream::WriteFloat(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
float f;
pH->GetParam(1,f);
m_pStm->Write(f);
return pH->EndFunction();
}
int CScriptObjectStream::WriteString(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *s;
pH->GetParam(1,s);
m_pStm->Write(s);
return pH->EndFunction();
}
int CScriptObjectStream::WriteBool(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
bool b;
pH->GetParam(1,b);
m_pStm->Write(b);
return pH->EndFunction();
}
int CScriptObjectStream::WriteNumberInBits(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int n;
int nNumOfBits;
pH->GetParam(1,n);
pH->GetParam(2,nNumOfBits);
m_pStm->WriteNumberInBits(n,nNumOfBits);
return pH->EndFunction();
}
int CScriptObjectStream::ReadInt(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
int n;
if(!m_pStm->Read(n))
return pH->EndFunctionNull();
return pH->EndFunction(n);
}
int CScriptObjectStream::ReadShort(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
short int n;
if(!m_pStm->Read(n))
return pH->EndFunctionNull();
return pH->EndFunction((int)n);
}
int CScriptObjectStream::ReadByte(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
unsigned char c;
if(!m_pStm->Read(c))
return pH->EndFunctionNull();
return pH->EndFunction((int)c);
}
int CScriptObjectStream::ReadFloat(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
float f;
if(!m_pStm->Read(f))
return pH->EndFunctionNull();
return pH->EndFunction(f);
}
int CScriptObjectStream::ReadString(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
char sTemp[256];
if(!m_pStm->Read(sTemp,256))
return pH->EndFunctionNull();
return pH->EndFunction(sTemp);
}
int CScriptObjectStream::ReadBool(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
bool b;
if(!m_pStm->Read(b))
return pH->EndFunctionNull();
return pH->EndFunction(b);
}
int CScriptObjectStream::ReadNumberInBits(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
unsigned int n;
int nNumOfBits;
pH->GetParam(1,nNumOfBits);
if(nNumOfBits<1 || nNumOfBits>32)
CryError( "CScriptObjectStream::ReadNumberInBits(%d) failed",nNumOfBits );
if(!m_pStm->ReadNumberInBits(n,nNumOfBits))
return pH->EndFunctionNull();
return pH->EndFunction((int)n);
}

View File

@@ -0,0 +1,63 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectStream.h: interface for the CScriptObjectStream class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTSTREAM_H__1E5E6A84_26DA_443B_B7D5_2E8896772A9B__INCLUDED_)
#define AFX_SCRIPTOBJECTSTREAM_H__1E5E6A84_26DA_443B_B7D5_2E8896772A9B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CStream;
/*! This class implements script-functions for exposing the bit stream functionalities
REMARKS:
this object doesn't have a global mapping(is not present as global variable into the script state)
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectStream :
public _ScriptableEx<CScriptObjectStream>
{
public:
CScriptObjectStream();
virtual ~CScriptObjectStream();
bool Create(IScriptSystem *pScriptSystem);
void Attach(CStream *pStm)
{
m_pStm=pStm;
}
public:
int WriteInt(IFunctionHandler *pH);
int WriteShort(IFunctionHandler *pH);
int WriteByte(IFunctionHandler *pH);
int WriteFloat(IFunctionHandler *pH);
int WriteString(IFunctionHandler *pH);
int WriteBool(IFunctionHandler *pH);
int WriteNumberInBits(IFunctionHandler *pH);
int ReadInt(IFunctionHandler *pH);
int ReadShort(IFunctionHandler *pH);
int ReadByte(IFunctionHandler *pH);
int ReadFloat(IFunctionHandler *pH);
int ReadString(IFunctionHandler *pH);
int ReadBool(IFunctionHandler *pH);
int ReadNumberInBits(IFunctionHandler *pH);
static void InitializeTemplate(IScriptSystem *pSS);
public:
CStream *m_pStm;
};
#endif // !defined(AFX_SCRIPTOBJECTSTREAM_H__1E5E6A84_26DA_443B_B7D5_2E8896772A9B__INCLUDED_)

View File

@@ -0,0 +1,149 @@
#include "stdafx.h"
#include "ScriptObjectSynched2DTable.h" // CScriptObjectSynched2DTable
#include "Synched2DTable.h" // CSynched2DTable
_DECLARE_SCRIPTABLEEX(CScriptObjectSynched2DTable)
void CScriptObjectSynched2DTable::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectSynched2DTable>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectSynched2DTable,SetEntryXY);
REG_FUNC(CScriptObjectSynched2DTable,GetEntryXY);
REG_FUNC(CScriptObjectSynched2DTable,GetEntryFloatXY);
REG_FUNC(CScriptObjectSynched2DTable,SetEntriesY);
REG_FUNC(CScriptObjectSynched2DTable,GetLineCount);
REG_FUNC(CScriptObjectSynched2DTable,GetColumnCount);
}
bool CScriptObjectSynched2DTable::Create(IScriptSystem *pScriptSystem, CSynched2DTable *pSynched2DTable)
{
m_pSynched2DTable=pSynched2DTable;
Init(pScriptSystem, this);
m_pScriptThis->RegisterParent(this);
// Function-Registration
return true;
}
int CScriptObjectSynched2DTable::SetEntryXY(IFunctionHandler *pH)
{
CHECK_PARAMETERS(3);
int iX,iY;
float fValue;
if(!pH->GetParam(1,iX))
return pH->EndFunction();
if(!pH->GetParam(2,iY))
return pH->EndFunction();
if(pH->GetParam(3,fValue))
{
m_pSynched2DTable->SetEntryXYFloat(iX,iY,fValue);
return pH->EndFunction();
}
else
{
char *szValue;
if(!pH->GetParam(3,szValue))
return pH->EndFunction();
if(szValue)
m_pSynched2DTable->SetEntryXYString(iX,iY,szValue);
}
return pH->EndFunction();
}
int CScriptObjectSynched2DTable::SetEntriesY(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int iY;
float fValue;
if(!pH->GetParam(1,iY))
return pH->EndFunction();
if(pH->GetParam(2,fValue))
{
m_pSynched2DTable->SetEntriesYFloat(iY,fValue);
return pH->EndFunction();
}
else
{
char *szValue;
if(!pH->GetParam(2,szValue))
return pH->EndFunction();
if(szValue)
m_pSynched2DTable->SetEntriesYString(iY,szValue);
}
return pH->EndFunction();
}
int CScriptObjectSynched2DTable::GetEntryFloatXY(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int iX,iY;
if(!pH->GetParam(1,iX))
return pH->EndFunction();
if(!pH->GetParam(2,iY))
return pH->EndFunction();
CSynched2DTable::STableEntry ref = m_pSynched2DTable->m_EntryTable.GetXY(iX,iY);
if(ref.IsFloat())
return pH->EndFunction(ref.GetFloat());
else
return pH->EndFunction(0.0f);
}
int CScriptObjectSynched2DTable::GetEntryXY(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
int iX,iY;
if(!pH->GetParam(1,iX))
return pH->EndFunction();
if(!pH->GetParam(2,iY))
return pH->EndFunction();
CSynched2DTable::STableEntry ref = m_pSynched2DTable->m_EntryTable.GetXY(iX,iY);
if(ref.IsFloat())
return pH->EndFunction(ref.GetFloat());
else
{
static char szOutBuffer[256];
strcpy(szOutBuffer,ref.GetString().c_str());
return pH->EndFunction(szOutBuffer);
}
}
int CScriptObjectSynched2DTable::GetLineCount(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction((int)m_pSynched2DTable->GetLineCount());
}
int CScriptObjectSynched2DTable::GetColumnCount(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
return pH->EndFunction((int)m_pSynched2DTable->GetColumnCount());
}

View File

@@ -0,0 +1,51 @@
#ifndef _SCRIPTOBJECTSYNCHED2DTABLE_H_
#define _SCRIPTOBJECTSYNCHED2DTABLE_H_
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
class CSynched2DTable;
/*! In this class are all Synched2DTable-related script-functions implemented.
IMPLEMENTATIONS NOTES:
These function will never be called from C-Code. They're script-exclusive.
*/
class CScriptObjectSynched2DTable : public _ScriptableEx<CScriptObjectSynched2DTable>, public IScriptObjectSink
{
public:
//! constructor
CScriptObjectSynched2DTable() {}
//! destructor
virtual ~CScriptObjectSynched2DTable() {}
//!
bool Create(IScriptSystem *pScriptSystem, CSynched2DTable *pSynched2DTable);
//!
void OnRelease()
{
m_pScriptThis=NULL;
delete this;
}
// is called from CXGame::Reset() to add the scripting
static void InitializeTemplate(IScriptSystem *pSS);
// script functions -----------------------------------------------
int SetEntryXY( IFunctionHandler *pH );
//! returns "" if the entry is not present
int GetEntryXY( IFunctionHandler *pH );
//! like GetEntryXY but returns 0.0 in case the value is not present or a string
int GetEntryFloatXY( IFunctionHandler *pH );
int SetEntriesY( IFunctionHandler *pH );
int GetColumnCount( IFunctionHandler *pH );
int GetLineCount( IFunctionHandler *pH );
private: // ---------------------------------------------------------
CSynched2DTable * m_pSynched2DTable; //!<
};
#endif //_SCRIPTOBJECTSYNCHED2DTABLE_H_

2135
CryGame/ScriptObjectUI.cpp Normal file

File diff suppressed because it is too large Load Diff

205
CryGame/ScriptObjectUI.h Normal file
View File

@@ -0,0 +1,205 @@
//-------------------------------------------------------------------------------------------------
// Author: M<>rcio Martins
//
// Purpose:
// - Make UI functions available from script as UI:Func(param)
//
// History:
// - [3/7/2003] created the file
//
//-------------------------------------------------------------------------------------------------
#pragma once
#include "UISystem.h"
class CScriptObjectUI : public _ScriptableEx<CScriptObjectUI>
{
public:
CScriptObjectUI(): m_pUISystem(0), m_pLog(0)
{
m_hCanRenderGame=
m_hCanSwitch=
m_hOnSwitch=
m_hOnInit=
m_hOnRelease=
m_hOnUpdate=
m_hOnDrawBackground=
m_hOnDrawMouseCursor=
m_hOnIdle=0;
};
~CScriptObjectUI() {};
int Create(CUISystem *pUISystem);
int Release();
int GetScriptFunctionPtrs();
int ReleaseScriptFunctionPtrs();
static void InitializeTemplate(IScriptSystem *pScriptSystem);
static void InitializeConstants(IScriptSystem *pScriptSystem);
//-------------------------------------------------------------------------------------------------
// Callback Functions, called by UISystem
//-------------------------------------------------------------------------------------------------
int CanRenderGame();
int CanSwitch(bool bIn);
int OnSwitch(bool bIn);
int OnInit();
int OnRelease();
int OnUpdate();
int OnDrawBackground();
int OnDrawMouseCursor();
int OnIdle(float fIdleTime);
//-------------------------------------------------------------------------------------------------
// Script Functions
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
int Release(IFunctionHandler *pH);
int Reload(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int GetWidget(IFunctionHandler *pH);
int GetWidgetCount(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int ShowWidget(IFunctionHandler *pH);
int HideWidget(IFunctionHandler *pH);
int IsWidgetVisible(IFunctionHandler *pH);
int EnableWidget(IFunctionHandler *pH);
int DisableWidget(IFunctionHandler *pH);
int IsWidgetEnabled(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SendMessage(IFunctionHandler *pH);
int BroadcastMessage(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SetBackground(IFunctionHandler *pH);
int GetBackground(IFunctionHandler *pH);
int SetBackgroundColor(IFunctionHandler *pH);
int GetBackgroundColor(IFunctionHandler *pH);
int ShowBackground(IFunctionHandler *pH);
int HideBackground(IFunctionHandler *pH);
int IsBackgroundVisible(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SetMouseXY(IFunctionHandler *pH);
int GetMouseXY(IFunctionHandler *pH);
int SetMouseCursor(IFunctionHandler *pH);
int GetMouseCursor(IFunctionHandler *pH);
int SetMouseCursorColor(IFunctionHandler *pH);
int GetMouseCursorColor(IFunctionHandler *pH);
int SetMouseCursorSize(IFunctionHandler *pH);
int GetMouseCursorWidth(IFunctionHandler *pH);
int GetMouseCursorHeight(IFunctionHandler *pH);
int ShowMouseCursor(IFunctionHandler *pH);
int HideMouseCursor(IFunctionHandler *pH);
int IsMouseCursorVisible(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SetGreyedColor(IFunctionHandler *pH);
int GetGreyedColor(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int CaptureMouse(IFunctionHandler *pH);
int ReleaseMouse(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int ExtractRed(IFunctionHandler *pH);
int ExtractGreen(IFunctionHandler *pH);
int ExtractBlue(IFunctionHandler *pH);
int ExtractAlpha(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int ExtractLeft(IFunctionHandler *pH);
int ExtractTop(IFunctionHandler *pH);
int ExtractWidth(IFunctionHandler *pH);
int ExtractHeight(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int GetMouseX(IFunctionHandler *pH);
int GetMouseY(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SetTopMostWidget(IFunctionHandler *pH);
int GetTopMostWidget(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SetFocus(IFunctionHandler *pH);
int GetFocus(IFunctionHandler *pH);
int SetFocusScreen(IFunctionHandler *pH);
int GetFocusScreen(IFunctionHandler *pH);
int FirstTabStop(IFunctionHandler *pH);
int LastTabStop(IFunctionHandler *pH);
int NextTabStop(IFunctionHandler *pH);
int PrevTabStop(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int CreateObjectFromTable(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int CreateScreenFromTable(IFunctionHandler *pH);
int GetScreenCount(IFunctionHandler *pH);
int GetScreen(IFunctionHandler *pH);
int ActivateScreen(IFunctionHandler *pH);
int DeactivateScreen(IFunctionHandler *pH);
int IsScreenActive(IFunctionHandler *pH);
int GetActiveScreenCount(IFunctionHandler *pH);
int DeactivateAllScreens(IFunctionHandler *pH);
int ActivateAllScreens(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int Disable(IFunctionHandler *pH);
int Enable(IFunctionHandler *pH);
int IsEnabled(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int StopAllVideo(IFunctionHandler *pH);
//-------------------------------------------------------------------------------------------------
int SetToolTipColor(IFunctionHandler *pH);
int GetToolTipColor(IFunctionHandler *pH);
int SetToolTipBorderColor(IFunctionHandler *pH);
int GetToolTipBorderColor(IFunctionHandler *pH);
int SetToolTipBorderSize(IFunctionHandler *pH);
int GetToolTipBorderSize(IFunctionHandler *pH);
int SetToolTipBorderStyle(IFunctionHandler *pH);
int GetToolTipBorderStyle(IFunctionHandler *pH);
int SetToolTipFontName(IFunctionHandler *pH);
int GetToolTipFontName(IFunctionHandler *pH);
int SetToolTipFontEffect(IFunctionHandler *pH);
int GetToolTipFontEffect(IFunctionHandler *pH);
int SetToolTipFontColor(IFunctionHandler *pH);
int GetToolTipFontColor(IFunctionHandler *pH);
int SetToolTipFontSize(IFunctionHandler *pH);
int GetToolTipFontSize(IFunctionHandler *pH);
private:
ILog *m_pLog;
CUISystem *m_pUISystem;
HSCRIPTFUNCTION m_hCanRenderGame;
HSCRIPTFUNCTION m_hCanSwitch;
HSCRIPTFUNCTION m_hOnSwitch;
HSCRIPTFUNCTION m_hOnInit;
HSCRIPTFUNCTION m_hOnRelease;
HSCRIPTFUNCTION m_hOnUpdate;
HSCRIPTFUNCTION m_hOnDrawBackground;
HSCRIPTFUNCTION m_hOnDrawMouseCursor;
HSCRIPTFUNCTION m_hOnIdle;
};

View File

@@ -0,0 +1,804 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectVehicle.cpp: implementation of the CScriptObjectVehicle class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "XPlayer.h"
#include "ScriptObjectVehicle.h"
#include "xvehicle.h"
#include "ScriptObjectVector.h"
#include "IAgent.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
_DECLARE_SCRIPTABLEEX(CScriptObjectVehicle)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CScriptObjectVehicle::CScriptObjectVehicle()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CScriptObjectVehicle::~CScriptObjectVehicle()
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Initializes the script-object and makes it available for the scripts.
@param pScriptSystem Pointer to the ScriptSystem-interface
@param pEntitySystem Pointer to the EntitySystem-interface
*/
bool CScriptObjectVehicle::Create(IScriptSystem *pScriptSystem, IEntitySystem *pEntitySystem)
{
m_pEntitySystem = pEntitySystem;
Init(pScriptSystem,this);
m_soContactPtVec.Create(pScriptSystem);
m_soSlipVelVec.Create(pScriptSystem);
m_pScriptThis->RegisterParent(this);
m_GetVehicleStatus.Create( pScriptSystem );
m_GetWheelStatus.Create( pScriptSystem );
return true;
}
//////////////////////////////////////////////////////////////////////////
void CScriptObjectVehicle::InitializeTemplate(IScriptSystem *pSS)
{
_ScriptableEx<CScriptObjectVehicle>::InitializeTemplate(pSS);
REG_FUNC(CScriptObjectVehicle,SetUser);
REG_FUNC(CScriptObjectVehicle,ReleaseUser);
//REG_FUNC(CScriptObjectVehicle,SetDriver);
//REG_FUNC(CScriptObjectVehicle,ReleaseDriver);
REG_FUNC(CScriptObjectVehicle,GetWheelStatus);
REG_FUNC(CScriptObjectVehicle,GetVehicleVelocity);
REG_FUNC(CScriptObjectVehicle,HasAccelerated);
REG_FUNC(CScriptObjectVehicle,IsBreaking);
REG_FUNC(CScriptObjectVehicle,WakeUp);
REG_FUNC(CScriptObjectVehicle,SetDrivingParameters);
REG_FUNC(CScriptObjectVehicle,SetCameraParameters);
REG_FUNC(CScriptObjectVehicle,SetWaterVehicleParameters);
REG_FUNC(CScriptObjectVehicle,SetVehicleEngineHealth);
//REG_FUNC(CScriptObjectVehicle,Explode);
REG_FUNC(CScriptObjectVehicle,SetGravity);
REG_FUNC(CScriptObjectVehicle,GetVertDeviation);
REG_FUNC(CScriptObjectVehicle,InitLights);
REG_FUNC(CScriptObjectVehicle,EnableLights);
REG_FUNC(CScriptObjectVehicle,SetWeaponLimits);
REG_FUNC(CScriptObjectVehicle,SetWeaponName);
// REG_FUNC(CScriptObjectVehicle,ShakePassengers);
REG_FUNC(CScriptObjectVehicle,GetVehicleStatus);
REG_FUNC(CScriptObjectVehicle,AnimateUsers);
REG_FUNC(CScriptObjectVehicle,HandBreak);
REG_FUNC(CScriptObjectVehicle,AnimateMountedWeapon);
AllowPropertiesMapping(pSS);
RegisterProperty( "velocity",PROPERTY_TYPE_FLOAT,offsetof(CVehicle,m_btVelocity));
RegisterProperty( "inwater",PROPERTY_TYPE_BOOL,offsetof(CVehicle,m_btInWater));
RegisterProperty( "turnState",PROPERTY_TYPE_INT,offsetof(CVehicle,m_TurnState));
RegisterProperty( "engineHealthReadOnly",PROPERTY_TYPE_FLOAT,offsetof(CVehicle,m_fEngineHealth)); // this should not be written ( not to
// break MP synchronization
}
//////////////////////////////////////////////////////////////////////////
void CScriptObjectVehicle::ReleaseTemplate( )
{
_ScriptableEx<CScriptObjectVehicle>::ReleaseTemplate();
}
/*! Attaches a vehicle-container.
@param pVehicle pointer to the vehicle-container which should be attached
*/
//////////////////////////////////////////////////////////////////////////
void CScriptObjectVehicle::SetVehicle(CVehicle *pVehicle)
{
m_pVehicle = pVehicle;
if(!EnablePropertiesMapping(pVehicle ))
{
CryError( "<CryGame> (CScriptObjectVehicle::SetVehicle) failed" );
return;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Retrieves the attached vehicle-container.
@return pointer to the attached vehicle-container
*/
CVehicle *CScriptObjectVehicle::GetVehicle()
{
return m_pVehicle;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::SetVehicleEngineHealth(IFunctionHandler *pH)
{
ASSERT(pH->GetParamCount()>=1);
float fEngineHealth;
pH->GetParam(1,fEngineHealth);
m_pVehicle->SetEngineHealth(fEngineHealth);
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Attaches a player to the vehicle, (so he is able to drive it IF bDriving).
@param nPlayerId id of the player which should be attached (int)
@param bDriving if 1-set driver, if 0-passenger
*/
int CScriptObjectVehicle::SetUser(IFunctionHandler *pH)
{
// ASSERT(pH->GetParamCount()>=3);
CHECK_PARAMETERS(5);
int parCount = pH->GetParamCount();
//FIXME
ILog *pLog=m_pVehicle->GetGame()->GetSystem()->GetILog();
//get the playerID
int nPlayerid;
pH->GetParam(1,nPlayerid);
//get the helper
const char *szHelperName;
if (!pH->GetParam(2,szHelperName))
szHelperName=NULL;
//check if an animation name is specified
const char * szAnimName;
if (!pH->GetParam(3,szAnimName))
szAnimName=NULL;
// check if we're setting this player as driver (can be a passenger also)
CPlayer::eInVehiclestate vehicleState = CPlayer::PVS_PASSENGER;
// int vehicleState = CPlayer::PVS_PASSENSER;
if (parCount>3)
pH->GetParam(4,(int&)vehicleState);
int iSlot=0;
pH->GetParam(5,iSlot);
// if no helper is specified, nobody knows where to place the player
if (!szHelperName)
{
pLog->Log("/003 CScriptObjectVehicle: Helper not specified");
return pH->EndFunction();
}
IEntity *pEntity = m_pEntitySystem->GetEntity(nPlayerid);
//CXServer *pSrv=m_pVehicle->GetGame()->GetServer();
//if (pSrv) // do server stuff
{
//bind the player to this vehicle
m_pVehicle->GetEntity()->Bind(nPlayerid,iSlot);
//pSrv->BindEntity(m_pVehicle->GetEntity()->GetId(),nPlayerid,iSlot); [Anton] - Entity->Bind already called the server
//make the player facing the correct angles
Vec3 hPos = Vec3(0,0,180);
pEntity->SetAngles(hPos);
// move the player to the correct position
m_pVehicle->GetEntity()->GetHelperPosition(szHelperName, hPos, true);
pEntity->SetPos( hPos, false );
//stop all animations
pEntity->ResetAnimations(0);
}
//start to play the "jump in vehicle" animation, if any
// if (szAnimName)
// pEntity->StartAnimation(0, szAnimName, 0, .15f);
CPlayer *pPlayer=NULL;
if (pEntity->GetContainer())
pEntity->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void**) &pPlayer);
if (!pPlayer)
{
pLog->Log("/004 CScriptObjectVehicle::SetUser trying to set nonplayer as user");
return pH->EndFunction();
}
// do not le him using the weapon once he's inside
// pPlayer->DeselectWeapon();
// Disable normal animation control so that it doesnt overide us
pPlayer->m_AnimationSystemEnabled = 0;
// let the player enter the vechicle as passenger or driver
pPlayer->EnterVehicle(m_pVehicle, vehicleState, szHelperName);
// if hes the driver, lets switch the control keys to the vechile keys
// the key map is changed from script
// deactivate the physics for the player
pEntity->ActivatePhysics( false );
//CLIENT side code
//play enter animation (if any)
pEntity->ResetAnimations(0);
if (szAnimName)
pEntity->StartAnimation(0,szAnimName, 0,.15f);
IAIObject *pObj=pEntity->GetAI();
return pH->EndFunction();
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::ReleaseUser(IFunctionHandler *pH)
{
// CHECK_PARAMETERS(3);
ASSERT(pH->GetParamCount()>=3);
int playerid;
pH->GetParam(1,playerid);
const char *szHelperName;
if (!pH->GetParam(2,szHelperName))
szHelperName=NULL;
const char *szAnimName;
if (!pH->GetParam(3,szAnimName))
szAnimName=NULL;
float angle;
if (!pH->GetParam(4,angle))
angle=0;
int iSlot=0;
pH->GetParam(5,iSlot);
IEntity *pEntity = m_pEntitySystem->GetEntity(playerid);
if(!pEntity)
return pH->EndFunction();
{
//do server side , if server present
//unbind the player on the server
m_pVehicle->GetEntity()->Unbind(playerid,iSlot);
//pSrv->UnbindEntity(m_pVehicle->GetEntity()->GetId(),playerid,iSlot); [Anton] entity already called the server
Vec3 vPos(0,0,0);
if (szHelperName)
{
m_pVehicle->GetEntity()->GetHelperPosition(szHelperName, vPos, false);
}
if ( (!szHelperName) || IsEquivalent(vPos,Vec3(0,0,0)) )
{
// if not helper is specified or not found, lets try to drop the player close
// to the vehicle
vPos=m_pVehicle->GetEntity()->GetPos();
vPos.z+=1; //move it 1 meter up to try to avoid collision problems
}
//[kirill] animation is reset in script, just to be sure
pEntity->ResetAnimations(0);
pEntity->SetPos(vPos);
// [Anton] this code seems useless
/*IPhysicalEntity *iphys = m_pVehicle->GetEntity()->GetPhysics();
if (iphys)
{
pe_status_dynamics dyn;
iphys->GetStatus( &dyn );
pEntity->AddImpulse(0, vPos, dyn.v*50 );
}*/
}
//play leaving animation, if any
CPlayer *pPlayer=NULL;
if(pEntity->GetContainer()) pEntity->GetContainer()->QueryContainerInterface(CIT_IPLAYER,(void**) &pPlayer);
if(!pPlayer)
{
m_pVehicle->GetGame()->GetSystem()->GetILog()->Log("/004 CScriptObjectVehicle::SetUser trying to set nonplayer as user");
return pH->EndFunction();
}
// enable normal animation control so that it doesnt overide us
pPlayer->m_AnimationSystemEnabled = 1;
if (pPlayer->IsAlive())
{
if (szAnimName)
pEntity->StartAnimation(0, szAnimName, 0, .0f);
}
if(m_pVehicle->m_DriverID == playerid)
{
IPhysicalEntity *pEnt=m_pVehicle->GetEntity()->GetPhysics();
pe_status_dynamics dyn;
pEnt->GetStatus( &dyn );
//no vel trheshold to brake the vehicle once exit, it feel better.
float velTrh = 0;//m_pVehicle->GetGame()->p_LeaveVehicleBrake->GetFVal();
velTrh *= velTrh;
if(pPlayer->IsAI() )
m_pVehicle->m_bBrakeOnNodriver = true;
else
m_pVehicle->m_bBrakeOnNodriver = (dyn.v.len2()<velTrh);
m_pVehicle->m_fNoDriverTime = 0.0f;
m_pVehicle->m_DriverID = 0;
}
pPlayer->LeaveVehicle();
// if (m_pVehicle->GetGame()->m_pIActionMapManager)
// m_pVehicle->GetGame()->m_pIActionMapManager->SetActionMap("default");
// activate the physics for the player
pEntity->ActivatePhysics( true );
if(pPlayer->IsMyPlayer() && pPlayer->IsAlive()) // user is killed and being released from vehicle - don't set camera to first person
m_pVehicle->GetGame()->SetViewMode(false); // set first person view mode
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Retrieves the current status of a certain wheel of the attached vehicle.
@param nWheel id of the wheel to retrieve the status from (int)
@return status table (bContact (bool), ptContact (vec), vel (float), dir (vec))
*/
int CScriptObjectVehicle::GetWheelStatus(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
//_SmartScriptObject pObj(m_pScriptSystem);
int nWheel;
pe_status_wheel Status;
pH->GetParam(1,nWheel);
m_pVehicle->GetWheelStatus(nWheel, &Status);
//CScriptObjectVector ContactPtVec(m_pScriptSystem);
//CScriptObjectVector SlipVelVec(m_pScriptSystem);
m_soContactPtVec=(Vec3)Status.ptContact;
m_soSlipVelVec=(Vec3)Status.velSlip;
float fSlipVel=Status.velSlip.len();
m_GetWheelStatus->SetValue( "bContact",Status.bContact );
m_GetWheelStatus->SetValue( "ptContact", m_soContactPtVec);
m_GetWheelStatus->SetValue( "vel", fSlipVel);
m_GetWheelStatus->SetValue( "dir", m_soSlipVelVec);
m_GetWheelStatus->SetValue( "compression", Status.suspLen/Status.suspLenFull);
//filippo: could be useful to get on what type of surface the wheel is contact
m_GetWheelStatus->SetValue( "surfaceIndex", Status.contactSurfaceIdx);
return pH->EndFunction(m_GetWheelStatus);
}
/*! Retrieves the vehicles velocity
@return velocity of the vehicle (float)
*/
//////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::GetVehicleVelocity(IFunctionHandler *pH)
{
//_SmartScriptObject pObj(m_pScriptSystem);
//pe_status_vehicle peStatus;
pe_status_dynamics peStatus;
CHECK_PARAMETERS(0);
IEntity *pEntity=m_pVehicle->GetEntity();
IPhysicalEntity *pPEnt=pEntity->GetPhysics();
if(pPEnt)
pPEnt->GetStatus(&peStatus);
float fVelocity=peStatus.v.len(); //.vel.len();
return pH->EndFunction(fVelocity);
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::GetVehicleStatus(IFunctionHandler *pH)
{
#if defined(LINUX)
IEntity *pEntity = NULL;
if(m_pVehicle)
pEntity=m_pVehicle->GetEntity();
else
return pH->EndFunction();
IPhysicalEntity *pPEnt = NULL;
if(pEntity)
pPEnt=pEntity->GetPhysics();
else
return pH->EndFunction();
#else
IEntity *pEntity=m_pVehicle->GetEntity();
IPhysicalEntity *pPEnt=pEntity->GetPhysics();
#endif
pe_status_vehicle peStatus;
if (pPEnt)
{
pPEnt->GetStatus(&peStatus);
m_GetVehicleStatus->BeginSetGetChain();
m_GetVehicleStatus->SetValueChain( "vel",peStatus.vel.len());
m_GetVehicleStatus->SetValueChain( "wheelcontact", peStatus.bWheelContact);
m_GetVehicleStatus->SetValueChain( "engineRPM", peStatus.engineRPM);
m_GetVehicleStatus->SetValueChain( "gear", peStatus.iCurGear-1);
m_GetVehicleStatus->SetValueChain( "clutch", peStatus.clutch);
//we want to know if lights are on/off
m_GetVehicleStatus->SetValueChain( "headlights", (m_pVehicle->m_bHeadLightsOn?1:0));
m_GetVehicleStatus->EndSetGetChain();
return pH->EndFunction(m_GetVehicleStatus);
}
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::WakeUp(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0);
IEntity *pEntity=m_pVehicle->GetEntity();
IPhysicalEntity *pPEnt=pEntity->GetPhysics();
if(pPEnt)
{
pe_params_pos params;
params.type = pe_params_pos::type_id;
params.iSimClass = 2;
pPEnt->SetParams(&params);
}
return pH->EndFunction( );
}
/*! Retrieves if the player started to accelerate the vehicle this frame
@return state of acceleration
*/
int CScriptObjectVehicle::HasAccelerated(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0)
return pH->EndFunction(m_pVehicle->HasAccelerated());
}
/*! Retrieves if the vehicle is breaking
@return state of acceleration
*/
int CScriptObjectVehicle::IsBreaking(IFunctionHandler *pH)
{
CHECK_PARAMETERS(0)
return pH->EndFunction(m_pVehicle->IsBreaking());
}
/*!
*/
int CScriptObjectVehicle::HandBreak(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1)
int bBreak=0;
pH->GetParam(1, bBreak);
m_pVehicle->m_bForceHandBreak = (bBreak!=0);
return pH->EndFunctionNull();
}
int CScriptObjectVehicle::SetDrivingParameters(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
_SmartScriptObject pTable(m_pScriptSystem,true);
pH->GetParam(1,*pTable);
float pedal_speed=10.0f,steer_speed=25.0f,max_steer_v0=40.0f,max_steer_kv=0.0f,steer_relaxation_v0=0.0f,steer_relaxation_kv=5.0f,
brake_vel_threshold=1000,brake_axle_friction=1000, max_steering_pedal=0.15f,pedal_limit_speed=10.0f;
float steer_speed_valScale = 0;
float steer_speed_min = 5;
//[filippo]
float fhandbrakevalue = 0.0f;
float fmaxbrakingfrictionnodriver = 0.0f;
float fhandbrakevaluenodriver = 0.0f;
float fstabilizejump = 0.0f;
float fsteerspeedscale = 1.0f;
float fsteerspeedscalemin = 2.0f;
//
pTable->GetValue("pedal_speed",pedal_speed);
pTable->GetValue("steer_speed",steer_speed);
pTable->GetValue("steer_speed_valScale",steer_speed_valScale);
pTable->GetValue("steer_speed_min",steer_speed_min);
pTable->GetValue("max_steer_v0",max_steer_v0);
pTable->GetValue("max_steer_kv",max_steer_kv);
pTable->GetValue("steer_relaxation_v0",steer_relaxation_v0);
pTable->GetValue("steer_relaxation_kv",steer_relaxation_kv);
pTable->GetValue("brake_vel_threshold",brake_vel_threshold);
pTable->GetValue("brake_axle_friction",brake_axle_friction);
pTable->GetValue("max_steering_pedal",max_steering_pedal);
pTable->GetValue("pedal_limit_speed",pedal_limit_speed);
//[filippo]
pTable->GetValue("handbraking_value",fhandbrakevalue);
pTable->GetValue("max_braking_friction_nodriver",fmaxbrakingfrictionnodriver);
pTable->GetValue("handbraking_value_nodriver",fhandbrakevaluenodriver);
pTable->GetValue("stabilize_jump",fstabilizejump);
pTable->GetValue("steer_speed_scale",fsteerspeedscale);
pTable->GetValue("steer_speed_scale_min",fsteerspeedscalemin);
//
if (m_pVehicle)
m_pVehicle->SetDrivingParams(pedal_speed, steer_speed, max_steer_v0,max_steer_kv, steer_relaxation_v0,steer_relaxation_kv,
brake_vel_threshold,brake_axle_friction, steer_speed_valScale, steer_speed_min, max_steering_pedal,pedal_limit_speed,
fhandbrakevalue,fmaxbrakingfrictionnodriver,fhandbrakevaluenodriver,fstabilizejump,fsteerspeedscale,fsteerspeedscalemin);
return pH->EndFunction(m_pVehicle!=0);
}
int CScriptObjectVehicle::SetCameraParameters(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
_SmartScriptObject pTable(m_pScriptSystem,true);
CScriptObjectVector oVec(m_pScriptSystem,true);
pH->GetParam(1,*pTable);
Vec3 vCamStiffness[2]={ Vec3(0,0,0),Vec3(0,0,0) },vCamLimits[2]={ Vec3(1,1,1),Vec3(1,1,1) };
float fCamDamping=0.8f,fMaxCamTimestep=0.01f,fCamSnapDist=0.001f,fCamSnapVel=0.01f;
if (pTable->GetValue("cam_stifness_negative",*oVec))
vCamStiffness[0] = oVec.Get();
if (pTable->GetValue("cam_stifness_positive",*oVec))
vCamStiffness[1] = oVec.Get();
if (pTable->GetValue("cam_limits_negative",*oVec))
vCamLimits[0] = oVec.Get();
if (pTable->GetValue("cam_limits_positive",*oVec))
vCamLimits[1] = oVec.Get();
pTable->GetValue("cam_damping",fCamDamping);
pTable->GetValue("cam_max_timestep",fMaxCamTimestep);
pTable->GetValue("cam_snap_dist",fCamSnapDist);
pTable->GetValue("cam_snap_vel",fCamSnapVel);
if (m_pVehicle)
m_pVehicle->SetCameraParams(vCamStiffness,vCamLimits,fCamDamping,fMaxCamTimestep,fCamSnapDist,fCamSnapVel);
return pH->EndFunction(m_pVehicle!=0);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::SetWaterVehicleParameters(IFunctionHandler *pH)
{
ASSERT(pH->GetParamCount()<=1);
// CHECK_PARAMETERS(1);
if(pH->GetParamCount()==1)
{
_SmartScriptObject pTable(m_pScriptSystem,true);
pH->GetParam(1,*pTable);
WATER_VEHICLE_PARAMS wvPar;
bool bFlyingVehicle=false;
pTable->GetValue("Damprot", wvPar.m_fBtDumpRot);
pTable->GetValue("Dampv", wvPar.m_fBtDumpV);
pTable->GetValue("Dampvs", wvPar.m_fBtDumpVSide);
pTable->GetValue("Dampvh", wvPar.m_fBtDumpVH);
pTable->GetValue("Dampw", wvPar.m_fBtDumpW);
pTable->GetValue("Turn", wvPar.m_fBtTurn);
wvPar.m_fBtTurnMin = wvPar.m_fBtTurn;
pTable->GetValue("TurnMin", wvPar.m_fBtTurnMin);
pTable->GetValue("TurnVelScale",wvPar.m_fBtTurnSpeedScale);
pTable->GetValue("Speedv", wvPar.m_fBtSpeedV);
pTable->GetValue("Speedturnmin",wvPar.m_fBtSpeedTurnMin);
pTable->GetValue("Stand", wvPar.m_fBtStand);
pTable->GetValue("WaveM", wvPar.m_fBtWave);
pTable->GetValue("TiltTurn", wvPar.m_fBtTitlTurn);
pTable->GetValue("TiltSpd", wvPar.m_fBtTitlSpd);
pTable->GetValue("TiltSpdA", wvPar.m_fBtTitlSpdA);
pTable->GetValue("TiltSpdMinV", wvPar.m_fBtTitlSpdMinV);
pTable->GetValue("TiltSpdMinVTilt", wvPar.m_fBtTitlSpdMinVTilt);
pTable->GetValue("DownRate", wvPar.m_fPgDownRate);
pTable->GetValue("BackUpRate", wvPar.m_fPgBackUpRate);
pTable->GetValue("BackUpSlowDwnRate", wvPar.m_fPgBackUpSlowRate);
pTable->GetValue("UpSpeedThrhld", wvPar.m_fPgUpSpeedThrhld);
pTable->GetValue("Flying", bFlyingVehicle);
pTable->GetValue("CameraDist", wvPar.m_fCameraDist);
wvPar.m_fBoatGravity = 0;//set a default gravity, now zero means to use the old system.
pTable->GetValue("gravity", wvPar.m_fBoatGravity);
wvPar.m_fBtStandAir = 0;
pTable->GetValue("StandInAir", wvPar.m_fBtStandAir);
//if no value for StandInAir is specified use the same value of Stand.
if (wvPar.m_fBtStandAir==0)
wvPar.m_fBtStandAir = wvPar.m_fBtStand;
if (m_pVehicle)
m_pVehicle->SetWaterVehicleParameters( wvPar, bFlyingVehicle );
}
else
{
if (m_pVehicle)
m_pVehicle->SetType(VHT_BOATDEAD);
}
return pH->EndFunction(m_pVehicle!=0);
}
//////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::SetGravity(IFunctionHandler *pH)
{
return (pH->EndFunction());
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::GetVertDeviation(IFunctionHandler *pH)
{
Vec3 upDir(0,0,1);
Matrix44 tm;
tm.SetIdentity();
tm=Matrix44::CreateRotationZYX(-m_pVehicle->GetEntity()->GetAngles()*gf_DEGTORAD)*tm; //NOTE: angles in radians and negated
upDir = GetTransposed44(tm)*upDir;
Vec3 cross = upDir.Cross( Vec3(0,0,1) );
float res = cross.len();
return pH->EndFunction(res);
}
//
//----------------------------------------------------------------------------------------------------------------
// helper, texture, headLeftHelper, headRightHelper, shader, backLeftHelper, backRightHelper, shader
int CScriptObjectVehicle::InitLights(IFunctionHandler *pH)
{
// ASSERT(pH->GetParamCount()>=3);
CHECK_PARAMETERS(8);
const char *szName;
if (!pH->GetParam(1,szName))
szName=NULL;
m_pVehicle->m_HeadLightHelper = szName;
if (!pH->GetParam(2,szName))
szName=NULL;
m_pVehicle->InitHeadLight(szName, NULL);//"LightBeam/0");
if (!pH->GetParam(3,szName))
szName=NULL;
m_pVehicle->m_HeadLightHelperLeft = szName;
if (!pH->GetParam(4,szName))
szName=NULL;
m_pVehicle->m_HeadLightHelperRight = szName;
if (!pH->GetParam(5,szName))
szName=NULL;
m_pVehicle->InitFakeLight(&m_pVehicle->m_pHeadLightLeft, szName);
m_pVehicle->InitFakeLight(&m_pVehicle->m_pHeadLightRight, szName);
if (!pH->GetParam(6,szName))
szName=NULL;
m_pVehicle->m_BackLightHelperLeft = szName;
if (!pH->GetParam(7,szName))
szName=NULL;
m_pVehicle->m_BackLightHelperRight = szName;
if (!pH->GetParam(8,szName))
szName=NULL;
m_pVehicle->InitFakeLight(&m_pVehicle->m_pBreakLightLeft, szName);
m_pVehicle->InitFakeLight(&m_pVehicle->m_pBreakLightRight, szName);
if(m_pVehicle->m_pHeadLight)
m_pVehicle->m_pHeadLight->m_nEntityLightId = 0;
if(m_pVehicle->m_pHeadLightLeft)
m_pVehicle->m_pHeadLightLeft->m_nEntityLightId = 1;
if(m_pVehicle->m_pHeadLightRight)
m_pVehicle->m_pHeadLightRight->m_nEntityLightId = 2;
if(m_pVehicle->m_pBreakLightLeft)
m_pVehicle->m_pBreakLightLeft->m_nEntityLightId = 3;
if(m_pVehicle->m_pBreakLightRight)
m_pVehicle->m_pBreakLightRight->m_nEntityLightId = 4;
return pH->EndFunction();
}
int CScriptObjectVehicle::EnableLights(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int lights=0;
pH->GetParam(1,lights);
m_pVehicle->m_bAutoLights = (lights!=0);
return pH->EndFunction();
}
int CScriptObjectVehicle::SetWeaponLimits(IFunctionHandler *pH)
{
CHECK_PARAMETERS(4);
pH->GetParam(1, m_pVehicle->m_MinVAngle);
pH->GetParam(2, m_pVehicle->m_MaxVAngle);
pH->GetParam(3, m_pVehicle->m_MinHAngle);
pH->GetParam(4, m_pVehicle->m_MaxHAngle);
m_pVehicle->m_AngleLimitVFlag = (m_pVehicle->m_MinVAngle!=m_pVehicle->m_MaxVAngle);
m_pVehicle->m_AngleLimitHFlag = (m_pVehicle->m_MinHAngle!=m_pVehicle->m_MaxHAngle);
return pH->EndFunction();
}
int CScriptObjectVehicle::SetWeaponName(IFunctionHandler *pH)
{
CHECK_PARAMETERS(2);
const char *wpnName;
pH->GetParam(1, wpnName);
m_pVehicle->m_sAutoWeaponName = wpnName;
pH->GetParam(2, wpnName);
m_pVehicle->m_sMountedWeaponName = wpnName;
return pH->EndFunction();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CScriptObjectVehicle::AnimateUsers(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
int aniId;
pH->GetParam(1, aniId);
CVehicle::UsersList::iterator usrIt=m_pVehicle->m_UsersList.begin();
for(; usrIt!=m_pVehicle->m_UsersList.end(); ++usrIt)
{
IEntity *pUsr = m_pEntitySystem->GetEntity( *usrIt );
if( pUsr )
pUsr->SendScriptEvent(ScriptEvent_InVehicleAnimation, aniId);
}
return pH->EndFunction();
}
int CScriptObjectVehicle::AnimateMountedWeapon(IFunctionHandler *pH)
{
CHECK_PARAMETERS(1);
const char *sanim_name=NULL;
pH->GetParam(1, sanim_name);
if (sanim_name && m_pVehicle && m_pVehicle->m_pEntity)
{
//GetISystem()->GetILog()->Log(sanim_name);
m_pVehicle->m_pEntity->StartAnimation(0, sanim_name, 0, 0 );
}
return pH->EndFunction();
}

View File

@@ -0,0 +1,95 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptObjectVehicle.h: interface for the CScriptObjectVehicle class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTOBJECTVEHICLE_H__2DADD57E_2A94_4A77_9BF3_D502BC12DA1D__INCLUDED_)
#define AFX_SCRIPTOBJECTVEHICLE_H__2DADD57E_2A94_4A77_9BF3_D502BC12DA1D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IScriptSystem.h>
#include <_ScriptableEx.h>
#include "ScriptObjectVector.h"
class CVehicle;
/*! This class implements all vehicle-related script-functions.
REMARKS:
After initialization of the script-object it will be accessable to vehicle-entities through scripts using the extension "cnt".
Example:
local wheelstats = VehicleEntity.cnt.GetWheelStatus( 0 );
*/
class CScriptObjectVehicle :
public IScriptObjectSink,
public _ScriptableEx<CScriptObjectVehicle>
{
public:
CVehicle *GetVehicle();
void SetVehicle(CVehicle *pPlayer);
CScriptObjectVehicle();
virtual ~CScriptObjectVehicle();
bool Create(IScriptSystem *pScriptSystem, IEntitySystem *);
int SetUser(IFunctionHandler *pH);
int ReleaseUser(IFunctionHandler *pH);
//int SetDriver(IFunctionHandler *pH);
//int ReleaseDriver(IFunctionHandler *pH);
int GetWheelStatus(IFunctionHandler *pH);
int GetVehicleVelocity(IFunctionHandler *pH);
int GetVehicleStatus(IFunctionHandler *pH);
int HasAccelerated(IFunctionHandler *pH);
int IsBreaking(IFunctionHandler *pH);
int HandBreak(IFunctionHandler *pH);
int WakeUp(IFunctionHandler *pH);
int SetDrivingParameters(IFunctionHandler *pH);
int SetCameraParameters(IFunctionHandler *pH);
int SetWaterVehicleParameters(IFunctionHandler *pH);
int SetVehicleEngineHealth(IFunctionHandler *pH);
int SetGravity(IFunctionHandler *pH);
//int Explode(IFunctionHandler *pH);
int GetVertDeviation(IFunctionHandler *pH);
int InitLights(IFunctionHandler *pH);
int EnableLights(IFunctionHandler *pH); // enable AI's to use lights
int SetWeaponName(IFunctionHandler *pH);
int SetWeaponLimits(IFunctionHandler *pH);
// int ShakePassengers(IFunctionHandler *pH);
int AnimateUsers(IFunctionHandler *pH);
int AnimateMountedWeapon(IFunctionHandler *pH); //!< animate the mounted weapon
// int SetDamage(IFunctionHandler *pH);
//IScriptObjectSink
void OnRelease()
{
m_pScriptThis=NULL;
delete this;
}
static void InitializeTemplate(IScriptSystem *pSS);
static void ReleaseTemplate( );
private:
CScriptObjectVector m_soSlipVelVec;
CScriptObjectVector m_soContactPtVec;
CVehicle *m_pVehicle;
IEntitySystem *m_pEntitySystem;
_SmartScriptObject m_GetVehicleStatus;
_SmartScriptObject m_GetWheelStatus;
};
#endif // !defined(AFX_SCRIPTOBJECTVEHICLE_H__2DADD57E_2A94_4A77_9BF3_D502BC12DA1D__INCLUDED_)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,97 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef SCRIPTOBJECTWEAPONCLASS_H__
#define SCRIPTOBJECTWEAPONCLASS_H__
#include <IScriptSystem.h>
#include <IEntitySystem.h>
#include <_ScriptableEx.h>
class CWeaponClass;
struct WeaponParams;
class CScriptObjectFireParam :
public _ScriptableEx<CScriptObjectFireParam>
{
public:
CScriptObjectFireParam();
virtual ~CScriptObjectFireParam();
bool Create(IScriptSystem *pScriptSystem,WeaponParams *p);
static void InitializeTemplate(IScriptSystem *pSS);
static void ReleaseTemplate();
private:
WeaponParams *m_pWeaponParams;
};
class CScriptObjectWeaponClass :
public _ScriptableEx<CScriptObjectWeaponClass>,
public IScriptObjectSink
{
public:
CScriptObjectWeaponClass();
virtual ~CScriptObjectWeaponClass();
bool Create(CXGame* pGame, CWeaponClass* pWeaponClass);
//IScriptObjectSink
void OnRelease()
{
m_pScriptThis->Clear();
m_pScriptThis=NULL;
delete this;
}
static void InitializeTemplate(IScriptSystem *pSS);
static void ReleaseTemplate();
int SetName(IFunctionHandler *pH);
int SetShaderFloat(IFunctionHandler *pH);
int SetBindBone(IFunctionHandler *pH);
int SetAnimationKeyEvent(IFunctionHandler *pH);
int StartAnimation(IFunctionHandler *pH);
int ResetAnimation(IFunctionHandler *pH);
int GetAnimationLength(IFunctionHandler *pH);
int GetCurAnimation(IFunctionHandler *pH);
int IsAnimationRunning(IFunctionHandler *pH);
int GetPos(IFunctionHandler *pH);
int GetBonePos(IFunctionHandler *pH);
int GetInstantHit(IFunctionHandler *pH);
int GetProjectileFiringAngle(IFunctionHandler *pH);
int Hit(IFunctionHandler *pH);
int SetFirstPersonWeaponPos(IFunctionHandler *pH);
int SetHoldingType(IFunctionHandler *pH);
int SetWeaponFireParams(IFunctionHandler *pH);
int LoadObject(IFunctionHandler *pH);
int AttachObjectToBone(IFunctionHandler *pH);
int DetachObjectToBone(IFunctionHandler *pH);
int CacheObject(IFunctionHandler *pH);
int DrawScopeFlare(IFunctionHandler *pH);
int CalcFlareIntensity(IFunctionHandler *pH);
public:
private:
typedef std::vector<CScriptObjectFireParam*> FireParamsObjVec;
typedef FireParamsObjVec::iterator FireParamsObjVecItor;
static void GetDirection(IEntity *pEntity, Vec3& vDir);
FireParamsObjVec m_vFireParams;
static IScriptObject *m_pMemberBonePos;
CWeaponClass* m_pWeaponClass;
CXGame* m_pGame;
ISystem* m_pSystem;
};
#endif //SCRIPTOBJECTWEAPONCLASS_H__

163
CryGame/ScriptTimerMgr.cpp Normal file
View File

@@ -0,0 +1,163 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptTimerMgr.cpp: implementation of the CScriptTimerMgr class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "EntityDesc.h"
#include "ScriptTimerMgr.h"
#include <IEntitySystem.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CScriptTimerMgr::CScriptTimerMgr(IScriptSystem *pScriptSystem,IEntitySystem *pS,IGame *pGame )
{
m_nLastTimerID=0;
m_pScriptSystem=pScriptSystem;
m_pEntitySystem=pS;
m_pGame=pGame;
m_bPause=false;
}
CScriptTimerMgr::~CScriptTimerMgr()
{
Reset();
}
//////////////////////////////////////////////////////////////////////////
// Create a new timer and put it in the list of managed timers.
int CScriptTimerMgr::AddTimer(IScriptObject *pTable,int64 nStartTimer,int64 nTimer,IScriptObject *pUserData,bool bUpdateDuringPause)
{
m_nLastTimerID++;
m_mapTempTimers.insert(ScriptTimerMapItor::value_type(m_nLastTimerID,new ScriptTimer(pTable,nStartTimer,nTimer,pUserData,bUpdateDuringPause)));
return m_nLastTimerID;
}
//////////////////////////////////////////////////////////////////////////
// Delete a timer from the list.
void CScriptTimerMgr::RemoveTimer(int nTimerID)
{
ScriptTimerMapItor itor;
// find timer
itor=m_mapTimers.find(nTimerID);
if(itor!=m_mapTimers.end())
{
// remove it
ScriptTimer *pST=itor->second;
delete pST;
m_mapTimers.erase(itor);
}
}
//////////////////////////////////////////////////////////////////////////
void CScriptTimerMgr::Pause(bool bPause)
{
m_bPause=bPause;
if (!m_pGame->GetModuleState(EGameMultiplayer))
m_pEntitySystem->PauseTimers(bPause);
}
//////////////////////////////////////////////////////////////////////////
// Remove all timers.
void CScriptTimerMgr::Reset()
{
ScriptTimerMapItor itor;
itor=m_mapTimers.begin();
while(itor!=m_mapTimers.end())
{
if(itor->second)
delete itor->second;
++itor;
}
m_mapTimers.clear();
itor=m_mapTempTimers.begin();
while(itor!=m_mapTempTimers.end())
{
if(itor->second)
delete itor->second;
++itor;
}
m_mapTempTimers.clear();
}
//////////////////////////////////////////////////////////////////////////
// Update all managed timers.
void CScriptTimerMgr::Update(int64 nCurrentTime)
{
ScriptTimerMapItor itor;
// loop through all timers.
itor=m_mapTimers.begin();
while(itor!=m_mapTimers.end())
{
ScriptTimer *pST=itor->second;
if (m_bPause && !pST->bUpdateDuringPause)
{
++itor;
continue;
}
// if it is time send a timer-event
if(((nCurrentTime-pST->nStartTime)>=pST->nTimer))
{
int id=0;
if(pST->pTable->GetValue("id",id))
{
IEntity *pEntity=m_pEntitySystem->GetEntity(id);
if(pEntity)
{
pEntity->SendScriptEvent(ScriptEvent_Timer,pST->pUserData?pST->pUserData:0);
}
}
else
{
HSCRIPTFUNCTION funcOnEvent;
if(pST->pTable->GetValue("OnEvent",funcOnEvent))
{
m_pScriptSystem->BeginCall(funcOnEvent);
m_pScriptSystem->PushFuncParam(pST->pTable);//self
m_pScriptSystem->PushFuncParam((int)ScriptEvent_Timer);
if(pST->pUserData)
m_pScriptSystem->PushFuncParam(pST->pUserData);
else
m_pScriptSystem->PushFuncParam(false);
m_pScriptSystem->EndCall();
}
}
// after sending the event we can remove the timer.
ScriptTimerMapItor tempItor=itor;
++itor;
m_mapTimers.erase(tempItor);
delete pST;
}
else
{
++itor;
}
}
// lets move all new created timers in the map. this is done at this point to avoid recursion, while trying to create a timer on a timer-event.
if(!m_mapTempTimers.empty())
{
ScriptTimerMapItor itor;
itor=m_mapTempTimers.begin();
while(itor!=m_mapTempTimers.end())
{
m_mapTimers.insert(ScriptTimerMapItor::value_type(itor->first,itor->second));
++itor;
}
m_mapTempTimers.clear();
}
}

67
CryGame/ScriptTimerMgr.h Normal file
View File

@@ -0,0 +1,67 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// ScriptTimerMgr.h: interface for the CScriptTimerMgr class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_SCRIPTTIMERMGR_H__D0CF3857_AEE5_4606_ADF9_549779C7DEEC__INCLUDED_)
#define AFX_SCRIPTTIMERMGR_H__D0CF3857_AEE5_4606_ADF9_549779C7DEEC__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <map>
//////////////////////////////////////////////////////////////////////////
struct ScriptTimer{
ScriptTimer(IScriptObject *_pTable,int64 _nStartTimer,int64 _nTimer,IScriptObject *_pUserData=NULL,bool _bUpdateDuringPause=true)
{
nTimer=_nTimer;
nStartTime=_nStartTimer;
pTable=_pTable;
pUserData=_pUserData;
bUpdateDuringPause=_bUpdateDuringPause;
}
~ScriptTimer()
{
if(pTable!=NULL)
pTable->Release();
if(pUserData!=NULL)
pUserData->Release();
}
int64 nTimer;
int64 nStartTime;
IScriptObject *pTable;
IScriptObject *pUserData;
bool bUpdateDuringPause;
};
typedef std::map<int,ScriptTimer *> ScriptTimerMap;
typedef ScriptTimerMap::iterator ScriptTimerMapItor;
//////////////////////////////////////////////////////////////////////////
class CScriptTimerMgr
{
public:
CScriptTimerMgr(IScriptSystem *pScriptSystem,IEntitySystem *pS,IGame *pGame);
virtual ~CScriptTimerMgr();
int AddTimer(IScriptObject *pTable,int64 nStartTimer,int64 nTimer,IScriptObject *pUserData,bool bUpdateDuringPause);
void RemoveTimer(int nTimerID);
void Update(int64 nCurrentTime);
void Reset();
void Pause(bool bPause);
private:
ScriptTimerMap m_mapTimers;
ScriptTimerMap m_mapTempTimers;
IScriptSystem *m_pScriptSystem;
IEntitySystem *m_pEntitySystem;
IGame *m_pGame;
int m_nLastTimerID;
bool m_bPause;
};
#endif // !defined(AFX_SCRIPTTIMERMGR_H__D0CF3857_AEE5_4606_ADF9_549779C7DEEC__INCLUDED_)

301
CryGame/Spectator.cpp Normal file
View File

@@ -0,0 +1,301 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <IEntitySystem.h>
#include "Game.h"
#include "spectator.h"
#include "XEntityProcessingCmd.h"
#include "XServer.h"
//////////////////////////////////////////////////////////////////////////
CSpectator::CSpectator(CXGame *pGame) :m_vAngles(0,0,0)
{
m_pScriptObject=NULL;
m_pGame=pGame;
m_eiHost=0;
m_fLastTargetSwitch=0.0f;
m_AreaUser.SetGame( pGame );
m_AreaUser.SetEntity( GetEntity() );
}
//////////////////////////////////////////////////////////////////////////
CSpectator::~CSpectator(void)
{
m_pGame->m_XAreaMgr.ExitAllAreas( m_AreaUser );
}
//////////////////////////////////////////////////////////////////////////
// Initialize the spectator-container.
bool CSpectator::Init()
{
IEntity *entity = GetEntity();
entity->GetScriptObject()->SetValue("type", "spectator");
// set camera
entity->SetCamera(m_pGame->GetSystem()->GetIEntitySystem()->CreateEntityCamera());
entity->GetCamera()->GetCamera().Init(m_pGame->GetSystem()->GetIRenderer()->GetWidth(),m_pGame->GetSystem()->GetIRenderer()->GetHeight());
m_pTimer=m_pGame->GetSystem()->GetITimer();
entity->SetNeedUpdate(true);
entity->SetNetPresence(true); // needed to sync m_eiHost
m_roll = 0;
float fMass=100.0f;
float fHeight=1.2f;
float fEyeHeight=1.7f;
float sphere_height=0.6f;
float radius=0.6f;
float fGravity=0.0f;
entity->CreateLivingEntity(fMass,fHeight,fEyeHeight,sphere_height,radius,-1,fGravity,true,true);
pe_player_dynamics pd;
pd.bActive = 1;
pd.kAirControl=1.0f;
pd.bSwimming=1;
entity->GetPhysics()->SetParams(&pd);
{
pe_params_flags pf;
pf.flagsAND=~(lef_push_players | lef_push_objects);
entity->GetPhysics()->SetParams(&pf);
}
{
pe_params_part pp;
pp.ipart=0;
pp.flagsAND=0;
entity->GetPhysics()->SetParams(&pp);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
// Update the camera.
void CSpectator::Update()
{
IEntity *pEntity=GetEntity();
m_pGame->ConstrainToSandbox(pEntity); // limit in the world boundaries
if(m_pGame->m_pServer) // detect if player was removed (not 100% accurate, might switch to different player)
{
bool bReset=false;
IEntity *pHost = m_pGame->GetSystem()->GetIEntitySystem()->GetEntity(m_eiHost);
if(pHost)
{
IEntityContainer *pICnt=pHost->GetContainer();
if(pICnt)
{
CPlayer *pPlayer;
if(!pICnt->QueryContainerInterface(CIT_IPLAYER,(void **)&pPlayer))
bReset=true;
}
else bReset=true;
}
else bReset=true;
if(bReset)
ResetHostId(); // host entity was removed
}
// only a client has to set the camera
if(m_pGame->IsClient())
{
IEntityCamera *pEC;
Vec3d v3Angles;
if(m_eiHost!=0)
return;
pEC=pEntity->GetCamera();
if(pEC)
{
pEC->SetAngles(m_vAngles);
pEC->SetPos(pEntity->GetPos()+Vec3(0,0,0.6f)); // 1.7m eye height
}
// update areas only for local spectator
if(IsMySpectator())
{
m_AreaUser.SetEntity(GetEntity());
m_pGame->m_XAreaMgr.UpdatePlayer( m_AreaUser );
}
}
}
//////////////////////////////////////////////////////////////////////////
EntityId CSpectator::GetHostId() const
{
return m_eiHost;
}
//////////////////////////////////////////////////////////////////////////
void CSpectator::ResetHostId()
{
m_eiHost=0;
}
//////////////////////////////////////////////////////////////////////////
void CSpectator::OnSetAngles( const Vec3d &ang ) {}
//////////////////////////////////////////////////////////////////////////
IScriptObject *CSpectator::GetScriptObject()
{
return m_pScriptObject;
}
//////////////////////////////////////////////////////////////////////////
void CSpectator::SetScriptObject(IScriptObject *object)
{
m_pScriptObject=object;
}
//////////////////////////////////////////////////////////////////////////
// Save upcast.
bool CSpectator::QueryContainerInterface(ContainerInterfaceType desired_interface, void **ppInterface )
{
if (desired_interface == CIT_ISPECTATOR)
{
*ppInterface = (void *) this;
return true;
}
else
{
*ppInterface = 0;
return false;
}
}
//////////////////////////////////////////////////////////////////////////
void CSpectator::GetEntityDesc( CEntityDesc &desc ) const
{
}
//////////////////////////////////////////////////////////////////////////
// Process input.
void CSpectator::ProcessKeys(CXEntityProcessingCmd &epc)
{
if(epc.CheckAction(ACTION_FIRE0))
{
if(m_pGame->m_pServer && (m_pTimer->GetCurrTime()-m_fLastTargetSwitch>1))
{
epc.RemoveAction(ACTION_FIRE0);
m_pGame->m_pServer->m_ServerRules.OnSpectatorSwitchModeRequest(m_pEntity);
m_fLastTargetSwitch=m_pTimer->GetCurrTime();
}
}
if(m_eiHost!=0)
return;
// fly-mode
Vec3d angles=epc.GetDeltaAngles();
m_vAngles=angles;
m_vAngles.x = max(m_vAngles.x,-65);
m_vAngles.x = min(m_vAngles.x,65);
epc.SetDeltaAngles(m_vAngles);
Vec3d pos=m_pEntity->GetPos();
int strafe = 0, move = 0;
if(epc.CheckAction(ACTION_MOVE_FORWARD)) move = 1;
if(epc.CheckAction(ACTION_MOVE_BACKWARD)) move = -1;
if(epc.CheckAction(ACTION_MOVE_LEFT)) strafe = -1;
if(epc.CheckAction(ACTION_MOVE_RIGHT)) strafe = 1;
Vec3d d;
d.x = (float)(move*cry_cosf(DEG2RAD(m_vAngles.z-90)));
d.y = (float)(move*cry_sinf(DEG2RAD(m_vAngles.z-90)));
d.x *= (float)cry_cosf(DEG2RAD(-m_vAngles.x));
d.y *= (float)cry_cosf(DEG2RAD(-m_vAngles.x));
d.z = (float)(move*cry_sinf(DEG2RAD(-m_vAngles.x)));
d.x += (float)(strafe*cry_cosf(DEG2RAD(m_vAngles.z-180)));
d.y += (float)(strafe*cry_sinf(DEG2RAD(m_vAngles.z-180)));
float curtime = m_pGame->m_pSystem->GetITimer()->GetFrameTime();
if (strafe==0)
{
m_roll = m_roll/(1+(float)cry_sqrtf(curtime*1000.0f)/25);
}
else
{
m_roll += strafe*curtime/-0.03f;
float maxroll = 3.0f;
if(m_roll>maxroll) m_roll = (float)maxroll;
if(m_roll<-maxroll) m_roll = (float)-maxroll;
};
m_vAngles.y = m_roll;
// move entity by physics
if(curtime)
{
pe_action_move motion;
motion.dt=curtime;
motion.dir=d*12.0f; // spectator speed is 12x
m_pEntity->GetPhysics()->Action(&motion);
}
}
//////////////////////////////////////////////////////////////////////////
bool CSpectator::Write(CStream &stm,EntityCloneState *cs)
{
return stm.Write(m_eiHost);
}
//////////////////////////////////////////////////////////////////////////
bool CSpectator::Read(CStream &stm)
{
return stm.Read(m_eiHost);
}
//////////////////////////////////////////////////////////////////////////
bool CSpectator::IsMySpectator() const
{
if(!m_pGame->m_pClient) return false;
return (m_pEntity->GetId()==m_pGame->m_pClient->GetPlayerId());
}
//////////////////////////////////////////////////////////////////////////
void CSpectator::OnEntityNetworkUpdate( const EntityId &idViewerEntity, const Vec3d &v3dViewer, uint32 &inoutPriority,
EntityCloneState &inoutCloneState ) const
{
bool bLocalPlayer = inoutCloneState.m_bLocalplayer;
if(!bLocalPlayer) // spectators are not sent to other player
inoutPriority=0; // no update at all
}

75
CryGame/Spectator.h Normal file
View File

@@ -0,0 +1,75 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
//////////////////////////////////////////////////////////////////////
#ifndef _SPECTATOR_H_
#define _SPECTATOR_H_
#include "GameObject.h"
#include <IEntitySystem.h>
#include "xarea.h"
class CXGame;
/*!implements the specatator container
this class is mainly used to parse the input of a the remote client
*/
class CSpectator :public CGameObject
{
public:
//! constructor
CSpectator(CXGame *pGame);
//! destructor
virtual ~CSpectator();
//!
void OnSetAngles( const Vec3 &ang );
//!
IScriptObject *GetScriptObject();
//!
void SetScriptObject(IScriptObject *object);
//!
bool IsMySpectator() const;
//!
void GetEntityDesc( CEntityDesc &desc ) const;
//!
void ProcessKeys(CXEntityProcessingCmd &epc);
//!
void PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime) {};
//!
EntityId GetHostId() const;
//! free the camera (no host following)
void ResetHostId();
// interface IEntityContainer ------------------------------------------------------------
virtual bool Init();
virtual void Update();
virtual bool Read(CStream &stm);
virtual bool Write(CStream &stm,EntityCloneState *cs=NULL);
virtual void OnDraw(const SRendParams & RendParams){};
virtual bool QueryContainerInterface( ContainerInterfaceType desired_interface, void **pInterface);
virtual void OnEntityNetworkUpdate( const EntityId &idViewerEntity, const Vec3d &v3dViewer, uint32 &inoutPriority,
EntityCloneState &inoutCloneState ) const;
private: // ---------------------------------------------------------------------------
EntityId m_eiHost; //!< 0 or the entity if we are currently spectating
IScriptObject * m_pScriptObject; //!<
CXGame * m_pGame; //!<
ITimer * m_pTimer; //!<
float m_roll; //!< roll angle
Vec3d m_vAngles; //!< in degrees
float m_fLastTargetSwitch; //!<
friend class CScriptObjectSpectator;
CXAreaUser m_AreaUser; //!<
};
#endif

14
CryGame/StdAfx.cpp Normal file
View File

@@ -0,0 +1,14 @@
// stdafx.cpp : source file that includes just the standard includes
// CryGame.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
#ifdef WIN64
int __cdecl strcmpi (const char *a, const char *b)
{
return stricmp (a,b);
}
#endif

388
CryGame/StdAfx.h Normal file
View File

@@ -0,0 +1,388 @@
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__B36C365D_F0EA_4545_B3BC_1E0EAB3B5E24__INCLUDED_)
#define AFX_STDAFX_H__B36C365D_F0EA_4545_B3BC_1E0EAB3B5E24__INCLUDED_
//#define _CRTDBG_MAP_ALLOC
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//////////////////////////////////////////////////////////////////////////
// THIS MUST BE AT THE VERY BEGINING OF STDAFX.H FILE.
// Disable STL threading support, (makes STL faster)
//////////////////////////////////////////////////////////////////////////
#define _NOTHREADS
#define _STLP_NO_THREADS
//////////////////////////////////////////////////////////////////////////
#ifdef _XBOX
// '<name>' name was marked as #pragma deprecated
//#pragma warning (disable : 4995)
#endif
// Insert your headers here
#include "platform.h"
#define REDUCED_FOR_PUBLIC_RELEASE // remark this if you want to get more network stats (but keep it out of every public build)
//#define NET_PACKET_LOGGING // pure netcode debug purpose - very slow networking - writes files to c:/temp
#ifdef GetClassName
#undef GetClassName
#endif
#include <stdlib.h>
#include <stdio.h>
#if defined(LINUX)
# include <stdarg.h>
# include "platform.h"
# include "IGame.h"
# include "string.h"
#endif
#if defined(_AMD64_) && !defined(LINUX)
#include <io.h>
#endif
#define USE_NEWPOOL
#include <CryMemoryManager.h>
/////////////////////////////////////////////////////////////////////////////
// VARIOUS MACROS ///////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#ifndef PS2
#if defined(WIN64) || defined(LINUX)
#define FIXME_ASSERT(cond) { if(!(cond)) abort(); }
#else
#define FIXME_ASSERT(cond) { if(!(cond)) { DEBUG_BREAK; } }
#endif
#else //PS2
#define FIXME_ASSERT(cond) { if(!(cond)) { FORCE_EXIT();} }
#endif
template <class T> inline void ZeroStruct( T &t ) { memset( &t,0,sizeof(t) ); }
#ifdef PS2
inline void __CRYTEKDLL_TRACE(const char *sFormat, ... )
#else
_inline void __cdecl __CRYTEKDLL_TRACE(const char *sFormat, ... )
#endif
{
va_list vl;
static char sTraceString[1024];
va_start(vl, sFormat);
vsprintf(sTraceString, sFormat, vl);
va_end(vl);
strcat(sTraceString, "\n");
::OutputDebugString(sTraceString);
}
#if 1
/*
#ifndef _XBOX
#ifdef WIN32
#include <windows.h>
#include <stdarg.h>
#endif
#else
#include <xtl.h>
#endif
*/
//Timur[9/3/2001] #include <windows.h>
/*
#define ASSERT(x) \
{ \
if (!(x)) { \
static char sAssertionMessage[1024]; \
\
sprintf(sAssertionMessage, "Assertion Failed!!\n\nFile: \"%s\"\n\nLine: %d\n", __FILE__, __LINE__); \
::MessageBox(NULL, sAssertionMessage, "Assertion Failed", MB_OK | MB_ICONERROR); \
DEBUG_BREAK; \
} \
} */
//#define ENABLE_NET_TRACE // enable for network debugging
//@FIXME this function should not be inline.
#define TRACE __CRYTEKDLL_TRACE
#ifdef ENABLE_NET_TRACE
#define NET_TRACE __CRYTEKDLL_TRACE
#else
# if defined(LINUX)
# define NET_TRACE //
# else
# define NET_TRACE __noop
# endif
#endif
#ifdef ASSERT
#undef ASSERT
#endif
#if defined(WIN64) || defined(LINUX64)
#define ASSERT(x) {assert(x);}
#else
#define ASSERT(x) { if (!(x)) { TRACE("Assertion Failed (%s) File: \"%s\" Line: %d\n", #x, __FILE__, __LINE__); DEBUG_BREAK; } }
#endif
#else
#define ASSERT(x)
#if defined(LINUX)
#undef assert
#define assert(exp) (void)( (exp) || (printf("Assert: ' %s ' has failed\n", #exp), 0) )
#undef ASSERT
#define ASSERT(exp) (void)( (exp) || (printf("Assert: ' %s ' has failed\n", #exp), 0) )
#endif
#ifndef PS2
#define TRACE 1?(void)0 : __CRYTEKDLL_TRACE;
#else
#define TRACE __CRYTEKDLL_TRACE;
#endif
#endif
#ifdef _DEBUG
#define _VERIFY(x) ASSERT(x)
#else
#define _VERIFY(x) x
#endif
/////////////////////////////////////////////////////////////////////////////
// STL //////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#pragma warning (disable : 4786)
#include <vector>
#include <list>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <memory>
#if defined(_DEBUG) && !defined(LINUX)
#include <crtdbg.h>
#define DEBUG_CLIENTBLOCK new( _NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_CLIENTBLOCK
#endif
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#endif
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
#endif
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
#endif
/////////////////////////////////////////////////////////////////////////////
// CRY Stuff ////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#include <Cry_Math.h>
#include <Cry_Camera.h>
/////////////////////////////////////////////////////////////////////////////
// Interfaces ///////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#include <ISystem.h>
#include <INetwork.h>
#include <IConsole.h>
#include <ILog.h>
#include <IInput.h>
#include <ITimer.h>
#include <IProcess.h>
//#include <I3DEngine.h>
#include <IEntitySystem.h>
#include <IPhysics.h>
#include <IRenderer.h>
#include "EntityDesc.h"
/////////////////////////////////////////////////////////////////////////////
// Classe used often/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
#include "IXSystem.h"
#include "GameShared.h"
/////////////////////////////////////////////////////////////////////////////
#include "Game.h"
#include "XNetwork.h"
#include "XServer.h"
#include "XServerSlot.h"
#include "XClient.h"
//////////////////////////////////////////////////////////////////////////
//! Reports a Game Warning to validator with WARNING severity.
inline void GameWarning( const char *format,... )
{
if (!format)
return;
char buffer[MAX_WARNING_LENGTH];
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
CryWarning( VALIDATOR_MODULE_GAME,VALIDATOR_WARNING,buffer );
}
//////////////////////////////////////////////////////////////////////////
inline void __DumpEntity(ILog *pLog,IEntity *pEntity)
{
const char *sTemp=NULL;
Vec3 v;
pLog->Log("************************************");
if(!pEntity)
{
pLog->Log("DUMPING ENTITY .... the pEntity IS NULL");
return;
}
pLog->Log("DUMPING ENTITY %d",pEntity->GetId());
pLog->Log("CLASSID [%03d]",(int)pEntity->GetClassId());
sTemp=pEntity->GetEntityClassName();
pLog->Log("GetClassName return [%p]",sTemp);
pLog->Log("CLASSNAME %s",sTemp);
sTemp=pEntity->GetName();
pLog->Log("GetName return [%p]",sTemp);
pLog->Log("NAME %s",sTemp);
v=pEntity->GetPos();
pLog->Log("POS %f,%f,%f",v.x,v.y,v.z);
pLog->Log("CONTAINER (ptr)[%p]",pEntity->GetContainer());
pLog->Log("************************************");
}
inline void __DumpEntity(ILog *pLog,const CEntityDesc &desc)
{
const char *sTemp=NULL;
Vec3 v;
pLog->Log("*************ENTITYDESCDUMP****************");
pLog->Log("CLASSID [%03d]",(int)desc.ClassId);
pLog->Log("CLASSNAME %s",desc.className.c_str());
v=desc.pos;
pLog->Log("POS %f,%f,%f",v.x,v.y,v.z);
pLog->Log("************************************");
}
//
//claps angl to be within min-max range. Check fro special case when min>max -- for example min=350 max=40
inline float ClampAngle360( float min, float max, float angl )
{
if(min>max)
{
if( angl>min || angl<max )
return angl;
if( fabs( angl-min )<fabs( angl-max ) )
angl = min;
else
angl = max;
return angl;
}
if( angl<min )
angl = min;
else if( angl>max )
angl = max;
return angl;
}
//
//gets angles difference, checks for case when a1 and a2 on different sides of 0. for example a1=350 a2=10
inline float GetAngleDifference360( float a1, float a2 )
{
float res = a1-a2;
if(res>180)
res = res-360;
else if(res<-180)
res = 360 + res;
return res;
}
//
// claps angl to be within min-max range. Check fro special case when min>max -- for example min=350 max=40
// all angles have to be in range (0, 360)
inline float ClampAngle( float minA, float maxA, float angl, bool &bClamped )
{
bClamped = false;
if(minA>maxA)
{
if( angl>minA || angl<maxA )
return angl;
}
else
if( angl>minA && angl<maxA )
return angl;
bClamped = true;
if( fabs(GetAngleDifference360(minA, angl)) < fabs(GetAngleDifference360(maxA, angl)) )
return minA;
return maxA;
}
//
// claps angl to be within min-max range. Check fro special case when min>max -- for example min=350 max=40
// all angles have to be in range (0, 360)
inline float ClampAngle( float minA, float maxA, float angl)
{
if(minA>maxA)
{
if( angl>minA || angl<maxA )
return angl;
}
else
if( angl>minA && angl<maxA )
return angl;
if( fabs(GetAngleDifference360(minA, angl)) < fabs(GetAngleDifference360(maxA, angl)) )
return minA;
return maxA;
}
#if !defined(min) && !defined(LINUX)
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
#endif
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__B36C365D_F0EA_4545_B3BC_1E0EAB3B5E24__INCLUDED_)

539
CryGame/StringTableMgr.cpp Normal file
View File

@@ -0,0 +1,539 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// StringTableMgr.cpp: implementation of the CStringTableMgr class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "StringTableMgr.h"
#include "ScriptObjectLanguage.h"
#include "IXMLDOM.h"
#include <StlUtils.h>
#include <IInput.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
CStringTableMgr::CStringTableMgr()
{
m_pSystem=NULL;
m_pLanguageStriptObject=NULL;
}
//////////////////////////////////////////////////////////////////////
CStringTableMgr::~CStringTableMgr()
{
}
//////////////////////////////////////////////////////////////////////
bool CStringTableMgr::Load(ISystem *pSystem,CScriptObjectLanguage &oLang, string sLanguage)
{
m_pSystem=pSystem;
m_sLanguage=sLanguage;
m_pLanguageStriptObject=&oLang;
m_vStrings.clear();
//-------------------------------------------------------------------------------------------------
// input localization
//-------------------------------------------------------------------------------------------------
// keyboard
for (int i = 0; i <= 0x80; i++)
{
AddControl(i);
}
// mouse
for (int i = 1; i <= 0x0f; i++)
{
AddControl(i*0x10000);
}
return (true);
}
void CStringTableMgr::AddControl(int nKey)
{
IInput *pInput = m_pSystem->GetIInput();
if (!pInput)
{
return;
}
wchar_t szwKeyName[256] = {0};
char szKey[256] = {0};
if (!IS_MOUSE_KEY(nKey))
{
if (pInput->GetOSKeyName(nKey, szwKeyName, 255))
{
sprintf(szKey, "control%d", nKey);
int nID = (int)m_vStrings.size();
m_keysMap[szKey] = nID;
m_vStrings.push_back(szwKeyName);
m_pLanguageStriptObject->AddString(szKey,nID);
sprintf(szKey, "%S", szwKeyName);
m_vEnglishStrings.push_back(szKey);
}
}
}
//////////////////////////////////////////////////////////////////////
// Retrieve a string by ID from the string-table.
const wstring & CStringTableMgr::EnumString(int nID) const
{
static wstring unknown (L"???");
if( nID<0 || nID>=int(m_vStrings.size()) )
return (unknown);// string doesnt exist, return "???"
return (m_vStrings[nID]);
}
//////////////////////////////////////////////////////////////////////
// Loads a string-table from a Excel XML Spreadsheet file.
bool CStringTableMgr::LoadExcelXmlSpreadsheet( const string &sFileName )
{
//string sPath="LANGUAGES/"+m_sLanguage+string("/")+sFileName;
string sPath="LANGUAGES/"+sFileName;
//check if this table has already been loaded
FileNamesMapItor nit = m_mapLoadedTables.find(sPath);
if (nit!=m_mapLoadedTables.end())
return (true);
XDOM::IXMLDOMDocumentPtr pDoc=m_pSystem->CreateXMLDocument();
// load xml-file
if (!pDoc->load(sPath.c_str()))
return (false);
m_mapLoadedTables[sFileName] = NULL;
XDOM::IXMLDOMNodeListPtr pNodeList;
XDOM::IXMLDOMNodePtr pString;
XDOM::IXMLDOMNodePtr pEnum;
XDOM::IXMLDOMNodePtr pValue;
XDOM::IXMLDOMNodeListPtr pWorksheetList = pDoc->getElementsByTagName("Worksheet");
pWorksheetList->reset();
XDOM::IXMLDOMNodePtr pWorksheetNode = pWorksheetList->nextNode();
if (!pWorksheetNode)
return false;
XDOM::IXMLDOMNodeListPtr pTableList = pWorksheetNode->getElementsByTagName("Table");
pTableList->reset();
XDOM::IXMLDOMNodePtr pTableNode = pTableList->nextNode();
if (!pTableNode)
return false;
XDOM::IXMLDOMNodeListPtr pRowsList = pTableNode->getElementsByTagName("Row");
XDOM::IXMLDOMNodePtr pRowNode;
XDOM::IXMLDOMNodePtr pCellNode;
int nRow = 0;
pRowsList->reset();
// get all strings in table
while (pRowNode = pRowsList->nextNode())
{
XDOM::IXMLDOMNodeListPtr pCellList = pRowNode->getElementsByTagName("Cell");
nRow++;
if (nRow == 1) // Skip first row, it only have description.
continue;
const char* sKeyString = "";
const char* sEnglishString = "";
const char* sLanguageString = "";
int nCell = 0;
pCellList->reset();
while (pCellNode = pCellList->nextNode())
{
XDOM::IXMLDOMNodeListPtr pDataList = pCellNode->getElementsByTagName("Data");
#if !defined(LINUX64)
if (pDataList==NULL)
#else
if (pDataList==0)
#endif
continue;
pDataList->reset();
XDOM::IXMLDOMNodePtr pDataNode = pDataList->nextNode();
if (!pDataNode)
continue;
//CellNode->getTex
switch (nCell)
{
// First cell is message key.
case 0:
sKeyString = pDataNode->getText();
break;
// Second cell is english message.
case 1:
sEnglishString = pDataNode->getText();
break;
// Third cell is local language.
case 2:
sLanguageString = pDataNode->getText();
break;
};
nCell++;
}
const char *sUTF_8_Str = sLanguageString;
if (strlen(sUTF_8_Str) == 0)
{
sUTF_8_Str = sEnglishString;
}
int nUTF_8_Len = strlen(sUTF_8_Str);
int nUnicodeLen = nUTF_8_Len + 16; // + 16 just for safety.
wchar_t *sUnicodeStr = new wchar_t[ nUnicodeLen*sizeof(wchar_t) + 16 ];
// Use UTF-8 multibyte unicode decoding to convert to wide string.
// This is potentially not porrtable, for different platforms, alternative function must be used.
#if defined(LINUX)
mbstowcs( sUnicodeStr, sUTF_8_Str, nUTF_8_Len );
sUnicodeStr[ nUTF_8_Len ] = 0;
#else
MultiByteToWideChar( CP_UTF8,0,sUTF_8_Str,-1,sUnicodeStr,nUnicodeLen );
#endif
wstring unicodeStr = sUnicodeStr;
wstring::size_type nPos;
while ((nPos = unicodeStr.find(L"\\n",0,2))!=wstring::npos)
{
unicodeStr.replace(nPos,2,L"\n");
}
SAFE_DELETE_ARRAY(sUnicodeStr);
if (m_keysMap.find(sKeyString) != m_keysMap.end())
{
//m_pSystem->GetILog()->Log("\003$6Localized String '%s' Already Loaded!", sKeyString);
}
else
{
int nID = (int)m_vStrings.size();
char szLowerCaseKey[1024];
strcpy(szLowerCaseKey,sKeyString);
strlwr(szLowerCaseKey);
m_vStrings.push_back( unicodeStr );
m_vEnglishStrings.push_back( sEnglishString );
m_keysMap[szLowerCaseKey] = nID;
m_pLanguageStriptObject->AddString( sKeyString,nID );
}
}
return (true);
}
//////////////////////////////////////////////////////////////////////////
// Loads a string-table from a XML-file.
bool CStringTableMgr::LoadStringTable(string sFileName)
{
return LoadExcelXmlSpreadsheet( sFileName );
/*
string sPath = "LANGUAGES/" + m_sLanguage + "/" + sFileName;
//check if this table has already been loaded
FileNamesMapItor nit = m_mapLoadedTables.find(sPath);
if (nit!=m_mapLoadedTables.end())
return (true);
XDOM::IXMLDOMDocumentPtr pDoc=m_pSystem->CreateXMLDocument();
// load xml-file
if (!pDoc->load(sPath.c_str()))
return (false);
m_mapLoadedTables[sFileName] = NULL;
XDOM::IXMLDOMNodeListPtr pNodeList;
XDOM::IXMLDOMNodePtr pString;
XDOM::IXMLDOMNodePtr pEnum;
XDOM::IXMLDOMNodePtr pValue;
pNodeList=pDoc->getElementsByTagName("string");
if(!pNodeList)
return true;
pNodeList->reset();
// get all strings in table
while (pString=pNodeList->nextNode())
{
pEnum=pString->getAttribute("enum");
pValue=pString->getAttribute("value");
if((pEnum!=NULL) && (pValue!=NULL))
{
wstring::size_type nPos;
int nID=m_vStrings.size();
//wstring str=pValue->getText();
wstring str=pValue->getTextW();
while ((nPos=str.find(L"\\n",0,2))!=wstring::npos)
{
str.replace(nPos,2,L"\n");
}
m_vStrings.push_back(str);
string keyString=pEnum->getText();
m_pLanguageStriptObject->AddString(pEnum->getText(),nID);
}
}
return (true);
*/
}
//////////////////////////////////////////////////////////////////////////
bool CStringTableMgr::LookupString( const char *sKey,wstring &sLocalizedString )
{
assert(sKey);
// Label sign.
if (sKey[0] == '@')
{
char szLowKey[512];
strcpy(szLowKey,sKey);
strlwr(szLowKey);
int nId = stl::find_in_map( m_keysMap,szLowKey,-1 );
if (nId >= 0)
{
sLocalizedString = m_vStrings[nId];
return true;
}
else
{
nId = stl::find_in_map( m_keysMap,szLowKey+1,-1 );
if (nId >= 0)
{
sLocalizedString = m_vStrings[nId];
return true;
}
else
{
//GameWarning( "Localized string for Label <%s> not found",sKey );
AppendToUnicodeString(sKey, sLocalizedString);
return false;
}
}
}
else
{
//GameWarning( "Not a valid localized string Label <%s>, must start with @ symbol",sKey );
}
AppendToUnicodeString(sKey, sLocalizedString);
return false;
}
//////////////////////////////////////////////////////////////////////////
bool CStringTableMgr::LookupEnglishString( const char *sKey, string &sLocalizedString )
{
assert(sKey);
// Label sign.
if (sKey[0] == '@')
{
char szLowKey[512];
strcpy(szLowKey,sKey);
strlwr(szLowKey);
int nId = stl::find_in_map( m_keysMap,szLowKey,-1 );
if (nId >= 0)
{
sLocalizedString = m_vEnglishStrings[nId];
return true;
}
else
{
nId = stl::find_in_map( m_keysMap,szLowKey+1,-1 );
if (nId >= 0)
{
sLocalizedString = m_vEnglishStrings[nId];
return true;
}
else
{
//GameWarning( "Localized string for Label <%s> not found",sKey );
AppendToAsciiString(sKey, sLocalizedString);
return false;
}
}
}
else
{
//GameWarning( "Not a valid localized string Label <%s>, must start with @ symbol",sKey );
}
AppendToAsciiString(sKey, sLocalizedString);
return false;
}
//////////////////////////////////////////////////////////////////////////
void CStringTableMgr::Localize(const string &sString, wstring &sLocalizedString, bool bEnglish )
{
// scan the string
bool done = false;
int len = sString.length();
int curpos = 0;
while (!done)
{
int pos = sString.find_first_of("@", curpos);
if (pos == string::npos)
{
// did not find anymore, so we are done
done = true;
pos = len;
}
// found an occurence
// we have skipped a few characters, so copy them over
if (pos > curpos)
{
// skip
AppendToUnicodeString(sString.substr(curpos, pos - curpos), sLocalizedString);
curpos = pos;
}
if (curpos == pos)
{
// find the end of the label
int endpos = sString.find_first_of(" ", curpos);
if (endpos == string::npos)
{
// have reached the end
done = true;
endpos = len;
}
if (endpos > curpos)
{
// localize token
if (bEnglish)
{
string sLocalizedToken;
LookupEnglishString(sString.substr(curpos, endpos - curpos).c_str(), sLocalizedToken);
AppendToUnicodeString(sLocalizedToken, sLocalizedString);
}
else
{
wstring sLocalizedToken;
LookupString(sString.substr(curpos, endpos - curpos).c_str(), sLocalizedToken);
// append
sLocalizedString+=sLocalizedToken;
}
curpos = endpos;
}
}
}
}
//////////////////////////////////////////////////////////////////////////
bool CStringTableMgr::GetSubtitleLabel(const char *_szFilename,char *szLabel)
{
if (!_szFilename || !szLabel)
return (false);
char szFilename[512];
strcpy(szFilename,_szFilename);
strlwr(szFilename);
ptrdiff_t len = strlen(szFilename)-1;
if (len<=1)
return (false);
char szFilenameCopy[512];
strcpy(szFilenameCopy,szFilename);
char *szIn=&szFilenameCopy[len];
// remove path
while ((len>0) && (*szIn) && (*szIn!='/') && (*szIn!='\\'))
{
szIn--;
len--;
}
szIn++;
len = strlen(szIn)-1;
if (len<=1)
return (false);
// strip extension
while (szIn[len])
{
if (szIn[len]=='.')
{
break;
}
len--;
if (!len)
{
return (false);
}
}
char szTemp[256];
strncpy(szTemp, szIn, len);
szTemp[len] = 0;
int nId = stl::find_in_map( m_keysMap,szTemp,-1 );
if (nId>=0)
{
// changed this, was copying szIn (original filename) into szLabel
sprintf(szLabel,"@%s",szTemp);
return (true);
}
return (false);
}
//////////////////////////////////////////////////////////////////////////
void CStringTableMgr::AppendToUnicodeString(const string& sSource, wstring &sDest)
{
std::vector<wchar_t> swTemp;
swTemp.resize(sSource.size()+1);
#if defined(LINUX)
swprintf (&swTemp[0], swTemp.size(), L"%S", sSource.c_str());
#else
swprintf (&swTemp[0], L"%S", sSource.c_str());
#endif
wstring tmp(&swTemp[0]);
sDest += tmp;
}
//////////////////////////////////////////////////////////////////////////
void CStringTableMgr::AppendToAsciiString(const string& sSource, string &sDest)
{
std::vector<char> sTemp;
sTemp.resize(sSource.size()+1);
sprintf (&sTemp[0], "%S", sSource.c_str());
string tmp(&sTemp[0]);
sDest += tmp;
}

65
CryGame/StringTableMgr.h Normal file
View File

@@ -0,0 +1,65 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// StringTableMgr.h: interface for the CStringTableMgr class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_STRINGTABLEMGR_H__892DBBEA_EC07_456B_8259_4A09006D8523__INCLUDED_)
#define AFX_STRINGTABLEMGR_H__892DBBEA_EC07_456B_8259_4A09006D8523__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//////////////////////////////////////////////////////////////////////
class CScriptObjectLanguage;
typedef std::map<string,void*> FileNamesMap;
typedef FileNamesMap::iterator FileNamesMapItor;
//////////////////////////////////////////////////////////////////////
/*!maps all language dependent string to a numeric id and
vice-versa it also expose the string id over the script
system
*/
class CStringTableMgr
{
public:
const wstring & EnumString(int nID) const;
///const string & EnumString(const char *szId);
CStringTableMgr();
virtual ~CStringTableMgr();
bool Load(ISystem *pSystem,CScriptObjectLanguage &oLang,string sLanguage);
bool LoadStringTable(string sFileName);
bool LoadExcelXmlSpreadsheet( const string &sFileName );
bool LookupString( const char *sKey, wstring &sLocalizedString );
bool LookupEnglishString( const char *sKey, string &sLocalizedString );
void Localize( const string &sString, wstring &sLocalizedString, bool bEnglish = false);
bool GetSubtitleLabel(const char *szFilename,char *szLabel);
private:
//! append the sSource string to the sDest string
void AppendToUnicodeString(const string& sSource, wstring &sDest);
void AppendToAsciiString(const string& sSource, string &sDest);
void AddControl(int nKey);
typedef std::map<string,int> StringsKeyMap;
std::vector<wstring> m_vStrings;
std::vector<string> m_vEnglishStrings;
StringsKeyMap m_keysMap;
string m_sLanguage;
//to keep track of the tables already loaded
FileNamesMap m_mapLoadedTables;
ISystem *m_pSystem;
CScriptObjectLanguage *m_pLanguageStriptObject;
};
#endif // !defined(AFX_STRINGTABLEMGR_H__892DBBEA_EC07_456B_8259_4A09006D8523__INCLUDED_)

493
CryGame/Synched2DTable.cpp Normal file
View File

@@ -0,0 +1,493 @@
#include "stdafx.h"
#include <IEntitySystem.h>
#include "Game.h"
#include "Synched2DTable.h" // CSynched2DTable
#include "XPlayer.h" // CPlayer
#include "Cry_Math.h" // TMatrix_tpl
#include <algorithm>
CSynched2DTable::CSynched2DTable(CXGame *pGame)
{
m_pScriptObject=NULL;
m_pGame=pGame;
}
//////////////////////////////////////////////////////////////////////////
// Initialize the AdvCamSystem-container.
bool CSynched2DTable::Init()
{
IEntity *entity = GetEntity();
entity->GetScriptObject()->SetValue("type", "Synched2DTable");
entity->SetNeedUpdate(true);
return true;
}
//////////////////////////////////////////////////////////////////////////
void CSynched2DTable::Update()
{
if(!GetISystem()->GetIGame()->GetModuleState(EGameServer))
return; // only needed on the server, does nothing on the client
IXGame *pXGame = GetIXGame( GetISystem()->GetIGame() ); assert(pXGame);
CXServer *pXServer = pXGame->GetServer(); assert(pXServer);
IServer *pIServer = pXServer->m_pIServer; assert(pIServer);
// check for disconnected clients
{
TDirtyListsMap::iterator itMap;
for(itMap=m_ServerslotDirtylist.begin();itMap!=m_ServerslotDirtylist.end();)
{
uint8 ucId=itMap->first;
if(!pIServer->GetServerSlotbyID(ucId))
{
// disconnected client
m_ServerslotDirtylist.erase(itMap++);
}
else
++itMap;
}
}
// check for new clients
{
// use uint32 not uin8 otherwise the for loop would not be able to teminate if we have 256 players
uint32 dwMaxClientID = (uint32)pIServer->GetMaxClientID();
for(uint32 dwId=0;dwId<=dwMaxClientID;++dwId)
{
IServerSlot *pSlot=pIServer->GetServerSlotbyID(dwId);
if(!pSlot)
continue; // disconnected
if(!m_ServerslotDirtylist.count(dwId))
InsertServerSlot(dwId); // new connected client
}
}
}
//////////////////////////////////////////////////////////////////////////
void CSynched2DTable::OnSetAngles( const Vec3d &ang )
{
}
//////////////////////////////////////////////////////////////////////////
IScriptObject *CSynched2DTable::GetScriptObject()
{
return m_pScriptObject;
}
//////////////////////////////////////////////////////////////////////////
void CSynched2DTable::SetScriptObject(IScriptObject *object)
{
m_pScriptObject=object;
}
//////////////////////////////////////////////////////////////////////////
// Save upcast.
bool CSynched2DTable::QueryContainerInterface(ContainerInterfaceType desired_interface, void **ppInterface )
{
/* if (desired_interface == CIT_IADVCAMSYSTEM)
{
*ppInterface = (void *) this;
return true;
}
else
*/
{
*ppInterface = 0;
return false;
}
}
void CSynched2DTable::GetEntityDesc( CEntityDesc &desc ) const
{
}
bool CSynched2DTable::STableEntry::Write( CStream &stm )
{
bool bFloat = m_fValue!=FLT_MAX;
stm.Write(bFloat);
if(bFloat)
return stm.Write(m_fValue);
else
return stm.Write(m_sValue);
}
bool CSynched2DTable::STableEntry::Read( CStream &stm )
{
bool bFloat;
if(!stm.Read(bFloat))
return false;
if(bFloat)
return stm.Read(m_fValue);
else
{
m_fValue=FLT_MAX;
return stm.Read(m_sValue);
}
}
bool CSynched2DTable::Write(CStream &stm,EntityCloneState *cs)
{
assert(cs);
uint8 ucClientId = cs->m_pServerSlot->GetID();
// true=send new packet, false=resend old packet
bool bSendNewPacket = cs->m_pServerSlot->OccupyLazyChannel();
bool SendOverLazyChannel=cs->m_pServerSlot->ShouldSendOverLazyChannel();
if(!SendOverLazyChannel)
{
if(!stm.Write(false)) // last one
return false;
return true;
}
TDirtyLists &list = m_ServerslotDirtylist[ucClientId].m_DirtyList;
if(m_ServerslotDirtylist[ucClientId].m_bPendingPacket && bSendNewPacket)
{
// got acknowledge from client so remove this
if(!list.empty())//[MG]pop_front remark: first element must not be empty, had a crash here, so trying to fix it with this...
list.pop_front();
// todo: remove
// GetISystem()->GetILog()->Log("CSynched2DTable got acknowledge from client so remove this");
}
if(!list.empty())
{
SDirtyItem &item = list.front();
m_ServerslotDirtylist[ucClientId].m_bPendingPacket=true;
if(!stm.Write(true)) // one item
return false;
bool bServerLazyState= cs->m_pServerSlot->GetServerLazyChannelState();
// todo: remove
// GetISystem()->GetILog()->Log("bServerLazyState write %s",bServerLazyState?"true":"false");
if(!stm.Write(bServerLazyState))
return false;
if(!stm.Write(item.m_ucX))
return false;
if(!stm.Write(item.m_ucY))
return false;
if(item.m_ucX==0xff)
{
// whole line
uint32 dwColumnCount=m_EntryTable.GetColumnCountY(item.m_ucY);
// todo: remove
// GetISystem()->GetILog()->Log("CSynched2DTable ucColumnCount write %d %d",(int)item.m_ucY,dwColumnCount);
if(!stm.Write((uint8)dwColumnCount))
return false;
for(uint32 dwX=0;dwX<dwColumnCount;++dwX)
{
STableEntry Value = m_EntryTable.GetXY(dwX,item.m_ucY);
if(!Value.Write(stm))
return false;
}
}
else
{
// one item
STableEntry Value = m_EntryTable.GetXY(item.m_ucX,item.m_ucY);
if(!Value.Write(stm))
return false;
}
}
if(!stm.Write(false)) // last one
return false;
return true;
}
bool CSynched2DTable::Read(CStream &stm)
{
for(;;)
{
bool bItem;
if(!stm.Read(bItem)) // if there are items
return false;
if(!bItem)
break;
bool bServerLazyState;
if(!stm.Read(bServerLazyState))
return false;
// todo: remove
// GetISystem()->GetILog()->Log("bServerLazyState read %s",bServerLazyState?"true":"false");
bool bIgnoreResentPacket=false;
if(m_pGame->GetClient()->GetLazyChannelState()==bServerLazyState)
bIgnoreResentPacket=true;
else
{
m_pGame->GetClient()->LazyChannelAcknowledge();
// todo: remove
// GetISystem()->GetILog()->Log("LazyChannelAcknowledge ->%s",m_pGame->GetClient()->GetLazyChannelState()?"true":"false");
}
uint8 ucX,ucY;
if(!stm.Read(ucX))
return false;
if(!stm.Read(ucY))
return false;
if(ucX==0xff) // (0xff is used to mark the whole line dirty)
{
// one line
uint8 ucColumnCount;
if(!stm.Read(ucColumnCount))
return false;
// todo: remove
// GetISystem()->GetILog()->Log("CSynched2DTable ucColumnCount read %d %d",(int)ucY,(int)ucColumnCount);
for(uint32 dwX=0;dwX<(uint32)ucColumnCount;++dwX)
{
STableEntry Value;
if(!Value.Read(stm))
return false;
// todo: remove
// GetISystem()->GetILog()->Log("CSynched2DTable receive %d %d %.2f",(int)dwX,(int)ucY,fValue);
if(!bIgnoreResentPacket)
m_EntryTable.SetXY(dwX,ucY,Value);
}
}
else
{
// one entry
STableEntry Value;
if(!Value.Read(stm))
return false;
// todo: remove
// GetISystem()->GetILog()->Log("CSynched2DTable receive %d %d %.2f",(int)ucX,(int)ucY,fValue);
if(!bIgnoreResentPacket)
m_EntryTable.SetXY(ucX,ucY,Value);
}
}
return true;
}
void CSynched2DTable::OnEntityNetworkUpdate( const EntityId &idViewerEntity, const Vec3d &v3dViewer, uint32 &inoutPriority,
EntityCloneState &inoutCloneState) const
{
inoutCloneState.m_bSyncAngles=false;
inoutCloneState.m_bSyncYAngle=false;
inoutCloneState.m_bSyncPosition=false;
// todo: set inoutPriority set based on not synched data count
inoutPriority=0xffff;
}
void CSynched2DTable::MarkDirty( const uint8 ucPlayerId )
{
TDirtyLists &list=m_ServerslotDirtylist[ucPlayerId].m_DirtyList;
list.clear();
uint32 dwLines=m_EntryTable.m_Lines.size();
for(uint32 dwI=0;dwI<dwLines;++dwI)
list.push_back(SDirtyItem(dwI));
}
void CSynched2DTable::MarkDirtyXY( const uint8 ucX, const uint8 ucY, const uint8 ucPlayerId )
{
TDirtyLists &list=m_ServerslotDirtylist[ucPlayerId].m_DirtyList;
SDirtyItem newEntry(ucX,ucY);
if(std::find(list.begin(),list.end(),newEntry) == list.end()) // if if wasn't in the list already
list.push_back(newEntry);
}
void CSynched2DTable::MarkDirtyY( const uint8 ucY, const uint8 ucPlayerId )
{
TDirtyLists &list=m_ServerslotDirtylist[ucPlayerId].m_DirtyList;
SDirtyItem newEntry(0xff,ucY);
if(std::find(list.begin(),list.end(),newEntry) == list.end()) // if if wasn't in the list already
list.push_back(newEntry);
}
void CSynched2DTable::MarkDirtyXY( const uint8 ucX, const uint8 ucY )
{
TDirtyListsMap::iterator itMap;
for(itMap=m_ServerslotDirtylist.begin();itMap!=m_ServerslotDirtylist.end();++itMap)
{
uint8 ucId=itMap->first;
MarkDirtyXY(ucX,ucY,ucId);
}
}
void CSynched2DTable::MarkDirtyY( const uint8 ucY )
{
TDirtyListsMap::iterator itMap;
for(itMap=m_ServerslotDirtylist.begin();itMap!=m_ServerslotDirtylist.end();++itMap)
{
uint8 ucId=itMap->first;
MarkDirtyY(ucY,ucId);
}
}
void CSynched2DTable::SetEntryXYFloat( const uint32 uiX, const uint32 uiY, const float fValue )
{
if(!GetISystem()->GetIGame()->GetModuleState(EGameServer))
{
assert(0); // only call this on the server
return; // to prevent crash
}
const STableEntry OldValue = m_EntryTable.GetXY(uiX,uiY);
// apply only changed values
if(!OldValue.IsFloat() || OldValue.GetFloat()!=fValue)
{
m_EntryTable.SetXY(uiX,uiY,fValue);
MarkDirtyXY(uiX,uiY);
}
}
void CSynched2DTable::SetEntryXYString( const uint32 uiX, const uint32 uiY, const string &sValue )
{
if(!GetISystem()->GetIGame()->GetModuleState(EGameServer))
{
assert(0); // only call this on the server
return; // to prevent crash
}
const STableEntry OldValue = m_EntryTable.GetXY(uiX,uiY);
// apply only changed values
if(OldValue.IsFloat() || OldValue.GetString()!=sValue)
{
m_EntryTable.SetXY(uiX,uiY,sValue.c_str());
MarkDirtyXY(uiX,uiY);
}
}
void CSynched2DTable::SetEntriesYFloat( const uint32 uiY, const float fValue )
{
if(!GetISystem()->GetIGame()->GetModuleState(EGameServer))
{
assert(0); // only call this on the server
return; // to prevent crash
}
uint32 dwColumns = m_EntryTable.GetColumnCountY(uiY);
for(uint32 iX=0;iX<dwColumns;++iX)
m_EntryTable.SetXY(iX,uiY,fValue);
MarkDirtyY(uiY);
}
void CSynched2DTable::SetEntriesYString( const uint32 uiY, const string &sValue )
{
if(!GetISystem()->GetIGame()->GetModuleState(EGameServer))
{
assert(0); // only call this on the server
return; // to prevent crash
}
uint32 dwColumns = m_EntryTable.GetColumnCountY(uiY);
for(uint32 iX=0;iX<dwColumns;++iX)
m_EntryTable.SetXY(iX,uiY,sValue.c_str());
MarkDirtyY(uiY);
}
void CSynched2DTable::InsertServerSlot( const uint8 ucId )
{
m_ServerslotDirtylist[ucId]=SDirtylist(); // create element
MarkDirty(ucId);
}
uint32 CSynched2DTable::GetLineCount() const
{
return m_EntryTable.m_Lines.size();
}
uint32 CSynched2DTable::GetColumnCount() const
{
return m_EntryTable.GetColumnCount();
}

305
CryGame/Synched2DTable.h Normal file
View File

@@ -0,0 +1,305 @@
#ifndef _SYNCHED2DTABLE_H_
#define _SYNCHED2DTABLE_H_
#include "GameObject.h"
#include <IEntitySystem.h>
#include <map> // STL map<,>
#include <list> // STL list<>
#include <vector> // STL vector<>
#include <float.h> // FLT_MAX
class CXGame;
//! for max 256 players
//! server table is synced to all clients
class CSynched2DTable : public CGameObject
{
public:
//! constructor
CSynched2DTable( CXGame *pGame );
//! destructor
virtual ~CSynched2DTable() {}
//! call this only on the server
void SetEntryXYFloat( const uint32 uiX, const uint32 uiY, const float fValue );
//! call this only on the server
void SetEntriesYFloat( const uint32 uiY, const float fValue );
//! call this only on the server
void SetEntryXYString( const uint32 uiX, const uint32 uiY, const string &sValue );
//! call this only on the server
void SetEntriesYString( const uint32 uiY, const string &sValue );
//!
uint32 GetLineCount() const;
//!
uint32 GetColumnCount() const;
// interface IEntityContainer -------------------------------
virtual bool Init();
virtual void Update();
virtual bool Write( CStream &stm, EntityCloneState *cs=NULL );
virtual bool Read( CStream &stm );
virtual IScriptObject *GetScriptObject( void );
virtual void SetScriptObject(IScriptObject *object);
virtual void OnSetAngles( const Vec3 &ang );
virtual void OnDraw( const SRendParams & RendParams ) {}
virtual bool QueryContainerInterface( ContainerInterfaceType desired_interface, void **pInterface);
virtual void GetEntityDesc( CEntityDesc &desc ) const;
void PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime) {};
virtual void OnEntityNetworkUpdate( const EntityId &idViewerEntity, const Vec3d &v3dViewer, uint32 &inoutPriority,
EntityCloneState &inoutCloneState ) const;
private: // -----------------------------------------------------------------------
struct STableEntry
{
//! constructor
STableEntry( const char *szString )
:m_fValue(FLT_MAX), m_sValue(szString)
{
}
//! constructor
STableEntry( const float fValue )
:m_fValue(fValue)
{
}
//! default constructor
STableEntry()
:m_fValue(FLT_MAX)
{
}
//! copy constructor
STableEntry( const STableEntry &Rhs )
{
m_fValue = Rhs.m_fValue;
m_sValue = Rhs.m_sValue;
}
//! assignment operator
STableEntry &operator=( const STableEntry &Rhs )
{
if(this==&Rhs)
return *this;
m_fValue = Rhs.m_fValue;
m_sValue = Rhs.m_sValue;
return *this;
}
//! only if IsFloat() returns true
float GetFloat() const
{
assert(IsFloat());
return m_fValue;
}
//! only if IsFloat() returns false
string GetString() const
{
assert(!IsFloat());
return m_sValue;
}
//!
void SetFloat( const float fValue )
{
assert(fValue!=FLT_MAX);
m_fValue=fValue;
}
//!
bool IsFloat() const
{
return m_fValue!=FLT_MAX;
}
//!
bool Write( CStream &stm );
//!
bool Read( CStream &stm );
private: //! ----------------------------------------------
float m_fValue; //!< currently we only support floats - we should extend this for strings as well
string m_sValue; //!< only used if m_fValue is FLT_MAX
};
// -----------------
struct STableLine
{
std::vector<STableEntry> m_Entries; //!<
//!
void EnsureSize( const uint32 uiX )
{
if(uiX>=m_Entries.size())
m_Entries.resize(uiX+1);
}
//!
void SetX( const uint32 uiX, const STableEntry &rValue )
{
if(uiX==0xff)
{ assert(0); return; } // (0xff is used to mark the whole line dirty)
EnsureSize(uiX);
m_Entries[uiX]=rValue;
}
//!
STableEntry GetX( const uint32 uiX )
{
if(uiX==0xff)
{ assert(0); return STableEntry(); } // (0xff is used to mark the whole line dirty)
if(uiX>=m_Entries.size())
return STableEntry();
return m_Entries[uiX];
}
uint32 GetColumnCount() const
{
return m_Entries.size();
}
};
// -----------------
struct STable
{
std::vector<STableLine> m_Lines; //!<
void EnsureSize( const uint32 uiY )
{
if(uiY>=m_Lines.size())
m_Lines.resize(uiY+1);
}
void SetXY( const uint32 uiX, const uint32 uiY, const STableEntry &rValue )
{
if(uiX==0xff)
{ assert(0); return; } // (0xff is used to mark the whole line dirty)
EnsureSize(uiY);
m_Lines[uiY].SetX(uiX,rValue);
}
STableEntry GetXY( const uint32 uiX, const uint32 uiY )
{
if(uiX==0xff)
{ assert(0); return STableEntry(); } // (0xff is used to mark the whole line dirty)
if(uiY>=m_Lines.size())
return STableEntry();
return m_Lines[uiY].GetX(uiX);
}
uint32 GetColumnCountY( const uint32 uiY ) const
{
assert(uiY<m_Lines.size());
return m_Lines[uiY].GetColumnCount();
}
uint32 GetColumnCount() const
{
uint32 dwRet=0;
std::vector<STableLine>::const_iterator it;
for(it=m_Lines.begin();it!=m_Lines.end();++it)
{
const STableLine &line = *it;
uint32 dwCnt = line.GetColumnCount();
dwRet = max(dwRet,dwCnt);
}
return dwRet;
}
};
// -----------------
//!
struct SDirtyItem
{
//! constructor (one entry)
SDirtyItem( const uint8 ucX, const uint8 ucY ) :m_ucX(ucX), m_ucY(ucY)
{
}
//! constructor (whole line)
SDirtyItem( const uint8 ucY ) :m_ucX(0xff), m_ucY(ucY)
{
}
//! comparison
bool operator==( const SDirtyItem &Rhs ) const
{
return m_ucX==Rhs.m_ucX && m_ucY==Rhs.m_ucY;
}
uint8 m_ucX; //!< coloumn (0xff is used to mark the whole line dirty)
uint8 m_ucY; //!< row
};
typedef std::list<SDirtyItem> TDirtyLists;
//! one per serverslot
struct SDirtylist
{
//! constructor
SDirtylist() :m_bFrameType(false), m_bPendingPacket(false)
{
}
TDirtyLists m_DirtyList; //!< should be quite small
bool m_bPendingPacket; //!< m_DirtyList.front() was already sent but no acknowledged
bool m_bFrameType; //!< alternating frame type is used as sliding window with size 1
};
typedef std::map<uint8,SDirtylist> TDirtyListsMap;
// ------------------------------------------------------------------------------
STable m_EntryTable; //!< current form of the table
IScriptObject * m_pScriptObject; //!< to fulfull the IEntityContainer interface
CXGame * m_pGame; //!< pointer to the game where we are, must not be 0
TDirtyListsMap m_ServerslotDirtylist; //!< [player id] = DirtyList
// ------------------------------------------------------------------------------
//! for one player, whole table
void MarkDirty( const uint8 ucPlayerId );
//! for all players, one entry
void MarkDirtyXY( const uint8 ucX, const uint8 ucY );
//! for one player, one entry
void MarkDirtyXY( const uint8 ucX, const uint8 ucY, const uint8 ucPlayerId );
//! for all players, whole line
void MarkDirtyY( const uint8 ucY );
//! for one player, whole line
void MarkDirtyY( const uint8 ucY, const uint8 ucPlayerId );
//!
void InsertServerSlot( const uint8 ucId );
friend class CScriptObjectSynched2DTable;
};
#endif // _SYNCHED2DTABLE_H_

View File

@@ -0,0 +1,138 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// History:
// 03/15/2003 MartinM created
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "synchedrandomseed.h"
#include "XPlayer.h" // CPlayer
float CSynchedRandomSeed::m_fRandomTable[]=
{
0.809f,0.585f,0.480f,0.350f,0.896f,0.823f,0.747f,0.174f,0.859f,0.711f,0.514f,0.304f,0.015f,0.091f,0.364f,0.147f,
0.166f,0.989f,0.446f,0.119f,0.005f,0.009f,0.378f,0.532f,0.571f,0.602f,0.607f,0.166f,0.663f,0.451f,0.352f,0.057f,
0.608f,0.783f,0.803f,0.520f,0.302f,0.876f,0.727f,0.956f,0.926f,0.539f,0.142f,0.462f,0.235f,0.862f,0.210f,0.780f,
0.844f,0.997f,1.000f,0.611f,0.392f,0.266f,0.297f,0.840f,0.024f,0.376f,0.093f,0.677f,0.056f,0.009f,0.919f,0.276f,
0.273f,0.588f,0.691f,0.838f,0.726f,0.485f,0.205f,0.744f,0.468f,0.458f,0.949f,0.744f,0.108f,0.599f,0.385f,0.735f,
0.609f,0.572f,0.361f,0.152f,0.225f,0.425f,0.803f,0.517f,0.990f,0.752f,0.346f,0.169f,0.657f,0.492f,0.064f,0.700f,
0.505f,0.147f,0.950f,0.142f,0.905f,0.693f,0.303f,0.427f,0.070f,0.967f,0.683f,0.153f,0.877f,0.822f,0.582f,0.191f,
0.178f,0.817f,0.475f,0.156f,0.504f,0.732f,0.406f,0.280f,0.569f,0.682f,0.756f,0.722f,0.475f,0.123f,0.368f,0.835f,
0.035f,0.517f,0.663f,0.426f,0.105f,0.949f,0.921f,0.550f,0.346f,0.472f,0.375f,0.847f,0.317f,0.456f,0.272f,0.983f,
0.298f,0.739f,0.567f,0.196f,0.761f,0.839f,0.398f,0.501f,0.890f,0.027f,0.995f,0.573f,0.051f,0.531f,0.194f,0.843f,
0.627f,0.658f,0.198f,0.842f,0.123f,0.110f,0.743f,0.314f,0.941f,0.286f,0.336f,0.140f,0.733f,0.835f,0.708f,0.600f,
0.747f,0.253f,0.144f,0.002f,0.061f,0.806f,0.853f,0.211f,0.116f,0.553f,0.014f,0.114f,0.455f,0.752f,0.686f,0.543f,
0.074f,0.437f,0.202f,0.696f,0.290f,0.437f,0.232f,0.578f,0.533f,0.629f,0.160f,0.504f,0.963f,0.696f,0.925f,0.190f,
0.336f,0.178f,0.995f,0.457f,0.998f,0.098f,0.625f,0.094f,0.438f,0.932f,0.048f,0.895f,0.290f,0.227f,0.769f,0.411f,
0.202f,0.628f,0.604f,0.452f,0.466f,0.598f,0.635f,0.855f,0.829f,0.625f,0.721f,0.566f,0.375f,0.184f,0.738f,0.555f,
0.905f,0.243f,0.189f,0.605f,0.699f,0.585f,0.351f,0.494f,0.080f,0.741f,0.612f,0.620f,0.691f,0.805f,0.149f,0.576f,
};
float CSynchedRandomSeed::GetRandTable(BYTE idx)
{
return m_fRandomTable[idx];
}
CSynchedRandomSeed::CSynchedRandomSeed()
{
m_ucRandomSeedCS=0; // inital value doesn't matter
m_ucStartRandomSeedCS=0;
m_bSynchToAllClientsS=true;
m_pParentPlayer=0;
}
CSynchedRandomSeed::~CSynchedRandomSeed()
{
}
void CSynchedRandomSeed::SetStartRandomSeedC( const uint8 Value )
{
assert(m_pParentPlayer);
m_ucStartRandomSeedCS=Value;
}
uint8 CSynchedRandomSeed::GetStartRandomSeedS()
{
return m_ucStartRandomSeedCS;
}
void CSynchedRandomSeed::SetParent( CPlayer *pPlayer )
{
assert(pPlayer);
m_pParentPlayer=pPlayer;
}
void CSynchedRandomSeed::IncreaseRandomSeedC()
{
assert(m_pParentPlayer); // call SetParent()
m_ucRandomSeedCS++; // 0..255 -> 0..255 -> ..
m_LastTimeRandomSeedChangedC = m_pParentPlayer->m_pTimer->GetCurrTimePrecise();
}
uint8 CSynchedRandomSeed::GetRandomSeedC()
{
assert(m_pParentPlayer); // call SetParent()
if(IsTimeToSyncToServerC())
{
if(!m_pParentPlayer->IsMyPlayer())
m_ucRandomSeedCS=m_ucStartRandomSeedCS;
}
return m_ucRandomSeedCS;
}
bool CSynchedRandomSeed::IsTimeToSyncToServerC()
{
assert(m_pParentPlayer); // call SetParent()
CTimeValue yet=m_pParentPlayer->m_pTimer->GetCurrTimePrecise();
CTimeValue PauseTime; PauseTime.SetMilliSeconds(300); // hard coded value, maybe dependent on the ping would be better
return yet-m_LastTimeRandomSeedChangedC > PauseTime;
}
uint8 CSynchedRandomSeed::GetStartRandomSeedC()
{
assert(m_pParentPlayer); // call SetParent()
if(IsTimeToSyncToServerC())
{
if(m_pParentPlayer->IsMyPlayer())
m_ucStartRandomSeedCS=m_ucRandomSeedCS;
}
return m_ucStartRandomSeedCS;
}
bool CSynchedRandomSeed::GetSynchToClientsS() const
{
return m_bSynchToAllClientsS;
}
void CSynchedRandomSeed::EnableSyncRandomSeedS( const uint8 Value )
{
m_ucStartRandomSeedCS=Value;
m_bSynchToAllClientsS=true;
}
void CSynchedRandomSeed::DisableSyncRandomSeedS()
{
m_bSynchToAllClientsS=false;
}

View File

@@ -0,0 +1,71 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// Description:
// random seed helper class (randomize the weapon bullet shooting)
// each player has a random seed the increases by one when used
// after a pause of not using it (e.g. 300ms) the value is constantly sent to the server.
// this stops again when using it.
// the server is distributing this info to the other players
// the result is a synchronized random seed value for every player
//
// History:
// 03/15/2003 MartinM created
//
//////////////////////////////////////////////////////////////////////
#ifndef SYNCHEDRANDOMSEED_H
#define SYNCHEDRANDOMSEED_H
#include "TimeValue.h" // CTimeValue
class CPlayer;
class CSynchedRandomSeed
{
public:
//! constructor
CSynchedRandomSeed();
//! destructor
virtual ~CSynchedRandomSeed();
//! \param pPlayer must not be 0
void SetParent( CPlayer *pPlayer );
//! detect pauses of usage (to sync the value)
bool IsTimeToSyncToServerC();
//! used to randomize the weapon bullet shooting
void IncreaseRandomSeedC();
//!
void SetStartRandomSeedC( const uint8 Value );
//! used to randomize the weapon bullet shooting
void EnableSyncRandomSeedS( const uint8 Value );
//!
void DisableSyncRandomSeedS();
//! used to randomize the weapon bullet shooting
uint8 GetRandomSeedC();
//! value we send to the server
uint8 GetStartRandomSeedC();
//! value we send to the clients
uint8 GetStartRandomSeedS();
//! \return true=we should send the seed value the clients, false otherwise
bool GetSynchToClientsS() const;
//!
static float GetRandTable( BYTE idx );
private: // --------------------------------------------------------------------------------
uint8 m_ucRandomSeedCS; //!< current value (used to randomize the weapon bullet shooting)
uint8 m_ucStartRandomSeedCS; //!< used to randomize the weapon bullet shooting, value we send to the server
CTimeValue m_LastTimeRandomSeedChangedC; //!< absolute time to detect pauses of usage
bool m_bSynchToAllClientsS; //!<
CPlayer * m_pParentPlayer; //!<
static float m_fRandomTable[256]; //!<
};
#endif // SYNCHEDRANDOMSEED_H

48
CryGame/TagPoint.h Normal file
View File

@@ -0,0 +1,48 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Source code
// Copyright (c) Crytek 2001-2004
//
// TagPoint.h: interface for the CTagPoint class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TAGPOINT_H__6BCD9697_65CE_496C_8B56_9EAFB4D006AD__INCLUDED_)
#define AFX_TAGPOINT_H__6BCD9697_65CE_496C_8B56_9EAFB4D006AD__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <IMarkers.h>
#include <string>
class CTagPoint : public ITagPoint
{
Vec3 m_vPosition;
Vec3 m_vAngles;
string m_sName;
CXGame *m_pGame;
public:
CTagPoint(CXGame *pGame){m_pGame = pGame;}
virtual ~CTagPoint(){};
virtual void SetPos(const Vec3 &pos) { m_vPosition = pos; }
virtual void GetPos(Vec3 &pos) { pos = m_vPosition; }
virtual void SetAngles(const Vec3 &angles) {m_vAngles = angles;}
virtual void GetAngles(Vec3 &angles) {angles = m_vAngles;}
virtual bool SetName(const char *pName) { return m_pGame->RenameTagPoint(m_sName,pName);}
virtual void OverrideName(const string &name) { m_sName = name;}
virtual char *GetName() { return (char *) m_sName.c_str(); }
void Release() { delete this; }
unsigned MemStats();
};
#endif // !defined(AFX_TAGPOINT_H__6BCD9697_65CE_496C_8B56_9EAFB4D006AD__INCLUDED_)

View File

@@ -0,0 +1,648 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: timedemorecorder.cpp
// Version: v1.00
// Created: 2/8/2003 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "TimeDemoRecorder.h"
#include <CryFile.h>
#include "Game.h"
#if defined(WIN32) && !defined(WIN64)
//#include "Psapi.h" // PSAPI is not supported on windows9x
//#pragma comment(lib,"Psapi.lib") // PSAPI is not supported on windows9x
#endif
//////////////////////////////////////////////////////////////////////////
// Brush Export structures.
//////////////////////////////////////////////////////////////////////////
#define TIMEDEMO_FILE_SIGNATURE "CRY"
#define TIMEDEMO_FILE_TYPE 150
#define TIMEDEMO_FILE_VERSION 1
#define FIXED_TIME_STEP 0.02f // Assume runing at 50fps.
#pragma pack(push,1)
struct STimeDemoHeader
{
char signature[3]; // File signature.
int filetype; // File type.
int version; // File version.
//////////////////////////////////////////////////////////////////////////
int numFrames;
float totalTime;
char reserved[128];
};
//////////////////////////////////////////////////////////////////////////
struct STimeDemoFrame
{
Vec3 pos;
Vec3 angles;
float frametime;
unsigned int nActionFlags[2];
float fLeaning;
int nPolygonsPerFrame;
char reserved[28];
};
#pragma pack(pop)
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CTimeDemoRecorder::CTimeDemoRecorder( ISystem *pSystem )
{
m_pSystem = pSystem;
assert(m_pSystem);
m_pGame = pSystem->GetIGame();
assert(m_pGame);
m_bRecording = false;
m_bPlaying = false;
m_currFrameIter = m_records.end();
m_recordStartTime = 0;
m_recordEndTime = 0;
m_lastFrameTime = 0;
m_totalDemoTime = 0;
m_recordedDemoTime = 0;
m_lastAveFrameRate = 0;
m_lastPlayedTotalTime = 0;
m_fixedTimeStep = 0;
m_maxLoops = 1000;
m_demo_scroll_pause = 1;
m_demo_noinfo = 1;
m_bPaused = false;
// Register demo variables.
pSystem->GetIConsole()->Register( "demo_num_runs",&m_maxLoops,1000,0,"Number of times to loop timedemo" );
pSystem->GetIConsole()->Register( "demo_scroll_pause",&m_demo_scroll_pause,1,0,"ScrollLock pauses demo play/record" );
pSystem->GetIConsole()->Register( "demo_noinfo",&m_demo_noinfo,0,0,"Disable info display during demo playback" );
pSystem->GetIConsole()->Register( "demo_quit",&m_demo_quit,0,0,"Quit game after demo runs finished" );
pSystem->GetIConsole()->Register( "demo_screenshot_frame",&m_demo_screenshot_frame,0,0,"Make screenshot on specified frame during demo playback" );
}
//////////////////////////////////////////////////////////////////////////
CTimeDemoRecorder::~CTimeDemoRecorder()
{
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::Record( bool bEnable )
{
if (bEnable == m_bRecording)
return;
m_bRecording = bEnable;
m_bPlaying = false;
if (m_bRecording)
{
// Start recording.
m_records.clear();
m_recordStartTime = GetTime();
m_lastFrameTime = m_recordStartTime;
StartSession();
}
else
{
// Stop recording.
m_recordedDemoTime = m_totalDemoTime;
m_lastFrameTime = GetTime();
StopSession();
}
m_currFrameIter = m_records.end();
m_currentFrame = 0;
m_totalDemoTime = 0;
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::Play( bool bEnable )
{
if (bEnable == m_bPlaying)
return;
if (m_records.empty())
return;
m_bRecording = false;
m_bPlaying = bEnable;
if (m_bPlaying)
{
LogInfo( "==============================================================" );
LogInfo( "TimeDemo Play Started , (Total Frames: %d, Recorded Time: %.2fs)",(int)m_records.size(),m_recordedDemoTime );
// Start demo playback.
m_currFrameIter = m_records.begin();
m_lastPlayedTotalTime = 0;
StartSession();
}
else
{
LogInfo( "TimeDemo Play Ended, (%d Runs Performed)",m_numLoops );
LogInfo( "==============================================================" );
// End demo playback.
m_currFrameIter = m_records.end();
m_lastPlayedTotalTime = m_totalDemoTime;
StopSession();
}
m_currentFrame = 0;
m_totalDemoTime = 0;
m_numLoops = 0;
m_fpsCounter = 0;
m_lastFpsTimeRecorded = GetTime();
m_currFPS = 0;
m_minFPS = 10000;
m_maxFPS = -10000;
m_nMaxPolys = INT_MIN;
m_nMinPolys = INT_MAX;
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::Save( const char *filename )
{
CCryFile file;
if (!file.Open( filename,"wb" ))
{
m_pSystem->Warning( VALIDATOR_MODULE_GAME,VALIDATOR_WARNING,0,filename,"Cannot open time demo file %s",filename );
return;
}
m_file = filename;
// Save Time demo file.
STimeDemoHeader hdr;
memset( &hdr,0,sizeof(hdr) );
memcpy( hdr.signature,TIMEDEMO_FILE_SIGNATURE,3 );
hdr.filetype = TIMEDEMO_FILE_TYPE;
hdr.version = TIMEDEMO_FILE_VERSION;
hdr.numFrames = m_records.size();
hdr.totalTime = m_recordedDemoTime;
file.Write( &hdr,sizeof(hdr) );
for (FrameRecords::iterator it = m_records.begin(); it != m_records.end(); ++it)
{
FrameRecord &rec = *it;
STimeDemoFrame frame;
frame.angles = rec.playerAngles;
frame.pos = rec.playerPos;
frame.frametime = rec.frameTime;
*frame.nActionFlags = *rec.nActionFlags;
frame.fLeaning = rec.fLeaning;
frame.nPolygonsPerFrame = rec.nPolygons;
file.Write( &frame,sizeof(frame) );
}
/*
XmlNodeRef root = m_pSystem->CreateXmlNode( "TimeDemo" );
root->setAttr( "TotalTime",m_recordedDemoTime );
for (FrameRecords::iterator it = m_records.begin(); it != m_records.end(); ++it)
{
FrameRecord &rec = *it;
XmlNodeRef xmlRecord = root->newChild( "Frame" );
xmlRecord->setAttr( "Pos",rec.playerPos );
xmlRecord->setAttr( "Ang",rec.playerAngles );
xmlRecord->setAttr( "Time",rec.frameTime );
}
root->saveToFile( filename );
*/
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::Load( const char *filename )
{
m_records.clear();
m_recordedDemoTime = 0;
m_totalDemoTime = 0;
CCryFile file;
if (!file.Open( filename,"rb" ))
{
m_pSystem->Warning( VALIDATOR_MODULE_GAME,VALIDATOR_WARNING,0,filename,"Cannot open time demo file %s",filename );
return;
}
m_file = filename;
// Load Time demo file.
STimeDemoHeader hdr;
file.Read( &hdr,sizeof(hdr) );
m_recordedDemoTime = hdr.totalTime;
m_totalDemoTime = m_recordedDemoTime;
for (int i = 0; i < hdr.numFrames && !file.IsEof(); i++)
{
STimeDemoFrame frame;
FrameRecord rec;
file.Read( &frame,sizeof(frame) );
rec.playerAngles = frame.angles;
rec.playerPos = frame.pos;
rec.frameTime = frame.frametime;
*rec.nActionFlags = *frame.nActionFlags;
rec.fLeaning = frame.fLeaning;
rec.nPolygons = frame.nPolygonsPerFrame;
m_records.push_back( rec );
}
/*
XmlNodeRef root = m_pSystem->LoadXmlFile( filename );
if (!root)
{
// No such demo file.
m_pSystem->Warning( VALIDATOR_MODULE_GAME,VALIDATOR_WARNING,0,filename,"Cannot open time demo file %s",filename );
return;
}
root->getAttr( "TotalTime",m_recordedDemoTime );
m_totalDemoTime = m_recordedDemoTime;
for (int i = 0; i < root->getChildCount(); i++)
{
FrameRecord rec;
XmlNodeRef xmlRecord = root->getChild(i);
xmlRecord->getAttr( "Pos",rec.playerPos );
xmlRecord->getAttr( "Ang",rec.playerAngles );
xmlRecord->getAttr( "Time",rec.frameTime );
m_records.push_back( rec );
}
*/
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::Update()
{
if (m_bRecording)
{
RecordFrame();
}
else if (m_bPlaying)
{
PlayFrame();
}
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::RecordFrame()
{
float time = GetTime();
float frameTime = time - m_lastFrameTime;
if (m_bPaused)
{
m_lastFrameTime = time;
return;
}
FrameRecord rec;
rec.frameTime = frameTime;
IEntity *pPlayer = NULL;
pPlayer = GetIXGame( m_pGame )->GetMyPlayer();
if (pPlayer)
{
rec.playerPos = pPlayer->GetPos();
rec.playerAngles = pPlayer->GetAngles();
}
// Record current processing command.
CXEntityProcessingCmd &cmd = ((CXGame*)m_pGame)->m_pClient->m_PlayerProcessingCmd;
*rec.nActionFlags = *cmd.m_nActionFlags;
rec.fLeaning = cmd.GetLeaning();
m_totalDemoTime += rec.frameTime;
int nPolygons,nShadowVolPolys;
m_pSystem->GetIRenderer()->GetPolyCount(nPolygons,nShadowVolPolys);
rec.nPolygons = nPolygons;
m_records.push_back( rec );
m_currentFrame++;
m_lastFrameTime = GetTime();
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::PlayFrame()
{
if (m_currFrameIter == m_records.end()) // can't playback empty records.
return;
float time = GetTime();
float frameTime = time - m_lastFrameTime;
if (m_bPaused)
{
m_lastFrameTime = time;
return;
}
FrameRecord &rec = *m_currFrameIter;
IEntity *pPlayer = NULL;
pPlayer = GetIXGame( m_pGame )->GetMyPlayer();
if (pPlayer)
{
pPlayer->SetPos( rec.playerPos );
pPlayer->SetAngles( rec.playerAngles );
GetIXGame( m_pGame )->SetViewAngles( rec.playerAngles );
}
// Overwrite current processing command.
CXEntityProcessingCmd &cmd = ((CXGame*)m_pGame)->m_pClient->m_PlayerProcessingCmd;
*cmd.m_nActionFlags = *rec.nActionFlags;
cmd.SetLeaning( rec.fLeaning );
m_totalDemoTime += frameTime;
int nPolygons,nShadowVolPolys;
m_pSystem->GetIRenderer()->GetPolyCount(nPolygons,nShadowVolPolys);
m_nPolysCounter += nPolygons;
m_nCurrPolys = nPolygons;
if (nPolygons > m_nMaxPolys)
m_nMaxPolys = nPolygons;
if (nPolygons < m_nMinPolys)
m_nMinPolys = nPolygons;
m_nTotalPolysRecorded += rec.nPolygons;
m_nTotalPolysPlayed += nPolygons;
//////////////////////////////////////////////////////////////////////////
// Calculate Frame Rates.
//////////////////////////////////////////////////////////////////////////
// Skip some frames before calculating frame rates.
if (time - m_lastFpsTimeRecorded > 1)
{
// Skip some frames before recording frame rates.
if (m_currentFrame > 60)
{
m_currFPS = (float)m_fpsCounter / (time - m_lastFpsTimeRecorded);
if (m_currFPS > m_maxFPS)
{
m_maxFPS_Frame = m_currentFrame;
m_maxFPS = m_currFPS;
}
if (m_currFPS < m_minFPS)
{
m_minFPS_Frame = m_currentFrame;
m_minFPS = m_currFPS;
}
}
m_nPolysPerSec = (int)(m_nPolysCounter / (time - m_lastFpsTimeRecorded));
m_nPolysCounter = 0;
m_fpsCounter = 0;
m_lastFpsTimeRecorded = time;
}
else
{
m_fpsCounter++;
}
//////////////////////////////////////////////////////////////////////////
m_currFrameIter++;
m_currentFrame++;
if(m_demo_screenshot_frame && m_currentFrame == m_demo_screenshot_frame)
{
/* ICVar * p_demo_file = pSystem->GetIConsole()->GetCVar("demo_file");
char szFileName[256]="";
sprinyf("demo_%s_%d.jpg",p_demo_file->GetString(),m_currentFrame);*/
m_pSystem->GetIRenderer()->ScreenShot();
}
// Play looped.
if (m_currFrameIter == m_records.end())
{
m_lastPlayedTotalTime = m_totalDemoTime;
m_lastAveFrameRate = GetAverageFrameRate();
// Log info to file.
LogRun();
m_totalDemoTime = 0;
m_currFrameIter = m_records.begin();
m_currentFrame = 0;
m_numLoops++;
m_nTotalPolysPlayed = 0;
m_nTotalPolysRecorded = 0;
// Stop playing if max runs reached.
if (m_numLoops > m_maxLoops)
{
Play(false);
if (m_demo_quit)
{
// Immidiate game abort after num loops done.
exit(0);
}
}
}
m_lastFrameTime = GetTime();
}
//////////////////////////////////////////////////////////////////////////
float CTimeDemoRecorder::GetTime()
{
// Must be asynchronius time, used for profiling.
return m_pSystem->GetITimer()->GetAsyncCurTime();
}
//////////////////////////////////////////////////////////////////////////
int CTimeDemoRecorder::GetNumFrames() const
{
return m_records.size();
}
//////////////////////////////////////////////////////////////////////////
float CTimeDemoRecorder::GetAverageFrameRate() const
{
float aveFrameTime = m_totalDemoTime / m_currentFrame;
float aveFrameRate = 1.0f / aveFrameTime;
return aveFrameRate;
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::RenderInfo()
{
if (m_demo_noinfo != 0)
return;
const char *sInfo = "";
m_bPaused = false;
if (m_bRecording || m_bPlaying)
{
if (m_demo_scroll_pause != 0 && GetISystem()->GetIInput())
{
bool bPaused = (GetISystem()->GetIInput()->GetKeyState(XKEY_SCROLLLOCK) & 1);
if (bPaused)
{
m_bPaused = true;
sInfo = " (Paused)";
}
}
}
IRenderer *pRenderer = m_pSystem->GetIRenderer();
if (m_bRecording)
{
float fColor[4] = {1,0,0,1};
pRenderer->Draw2dLabel( 1,1, 1.3f, fColor,false,"Recording TimeDemo%s, Frames: %d",sInfo,m_currentFrame );
}
else if (m_bPlaying)
{
float aveFrameRate = GetAverageFrameRate();
int numFrames = GetNumFrames();
float fColor[4] = {0,1,0,1};
pRenderer->Draw2dLabel( 1,1, 1.3f, fColor,false,"Playing TimeDemo%s, Frame %d of %d (Looped: %d)",sInfo,m_currentFrame,numFrames,m_numLoops );
pRenderer->Draw2dLabel( 1,1+15, 1.3f, fColor,false,"Last Played Length: %.2fs, FPS: %.2f",m_lastPlayedTotalTime,m_lastAveFrameRate );
pRenderer->Draw2dLabel( 1,1+30, 1.3f, fColor,false,"Average FPS: %.2f, FPS: %.2f, Polys/Frame: %d",aveFrameRate,m_currFPS,m_nCurrPolys );
pRenderer->Draw2dLabel( 1,1+45, 1.3f, fColor,false,"Polys Rec/Play Ratio: %.2f",(float)m_nTotalPolysRecorded/m_nTotalPolysPlayed );
}
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::SetConsoleVar( const char *sVarName,float value )
{
ICVar *pVar = m_pSystem->GetIConsole()->GetCVar( sVarName );
if (pVar)
pVar->Set( value );
}
//////////////////////////////////////////////////////////////////////////
float CTimeDemoRecorder::GetConsoleVar( const char *sVarName )
{
ICVar *pVar = m_pSystem->GetIConsole()->GetCVar( sVarName );
if (pVar)
return pVar->GetFVal();
return 0;
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::StartSession()
{
m_nTotalPolysRecorded = 0;
m_nTotalPolysPlayed = 0;
m_lastAveFrameRate = 0;
m_lastPlayedTotalTime = 0;
// Register to frame profiler.
m_pSystem->GetIProfileSystem()->AddPeaksListener( this );
// Remember old time step, and set constant one.
m_fixedTimeStep = GetConsoleVar( "fixed_time_step" );
SetConsoleVar( "fixed_time_step",FIXED_TIME_STEP );
SetConsoleVar( "ai_ignoreplayer",1 );
SetConsoleVar( "ai_soundperception",0 );
SetConsoleVar( "mov_NoCutscenes",1 );
// Profile
m_oldPeakTolerance = GetConsoleVar( "profile_peak" );
SetConsoleVar( "profile_peak",50 );
m_lastFrameTime = GetTime();
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::StopSession()
{
// Set old time step.
SetConsoleVar( "fixed_time_step",m_fixedTimeStep );
SetConsoleVar( "ai_ignoreplayer",0 );
SetConsoleVar( "ai_soundperception",1 );
SetConsoleVar( "mov_NoCutscenes",0 );
// Profile.
SetConsoleVar( "profile_peak",m_oldPeakTolerance );
m_pSystem->GetIProfileSystem()->RemovePeaksListener( this );
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::LogInfo( const char *format,... )
{
if (m_demo_noinfo != 0)
return;
va_list ArgList;
char szBuffer[1024];
va_start(ArgList, format);
vsprintf(szBuffer, format, ArgList);
va_end(ArgList);
char path_buffer[_MAX_PATH];
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
m_pSystem->GetILog()->Log( szBuffer );
_splitpath( m_file.c_str(), drive, dir, fname, ext );
_makepath( path_buffer, drive, dir,fname,"log" );
FILE *hFile = fopen( path_buffer,"at" );
if (hFile)
{
// Write the string to the file and close it
fprintf(hFile, "%s\n",szBuffer );
fclose(hFile);
}
}
//////////////////////////////////////////////////////////////////////////
void CTimeDemoRecorder::OnFrameProfilerPeak( CFrameProfiler *pProfiler,float fPeakTime )
{
if (m_bPlaying && !m_bPaused)
{
LogInfo( " -Peak at Frame %d, %.2fms : %s (count: %d)",m_currentFrame,fPeakTime,pProfiler->m_name,pProfiler->m_count );
}
}
void CTimeDemoRecorder::LogRun()
{
int numFrames = m_records.size();
LogInfo( "!TimeDemo Run %d Finished.",m_numLoops );
LogInfo( " Play Time: %.2fs, Average FPS: %.2f",m_lastPlayedTotalTime,m_lastAveFrameRate );
LogInfo( " Min FPS: %.2f at frame %d, Max FPS: %.2f at frame %d",m_minFPS,m_minFPS_Frame,m_maxFPS,m_maxFPS_Frame );
LogInfo( " Average Tri/Sec: %d, Tri/Frame: %d",(int)(m_nTotalPolysPlayed/m_lastPlayedTotalTime),m_nTotalPolysPlayed/numFrames );
LogInfo( " Recorded/Played Tris ratio: %.2f",(float)m_nTotalPolysRecorded/m_nTotalPolysPlayed );
#if defined(WIN32) && !defined(WIN64)
// PSAPI is not supported on window9x
// so, don't use it
//PROCESS_MEMORY_COUNTERS pc;
//HANDLE hProcess = GetCurrentProcess();
//pc.cb = sizeof(pc);
//GetProcessMemoryInfo( hProcess,&pc,sizeof(pc) );
//int MB = 1024*1024;
//LogInfo( " Memory Usage: WorkingSet=%dMb, PageFile=%dMb, PageFaults=%d",pc.WorkingSetSize/MB,pc.PagefileUsage/MB,pc.PageFaultCount );
#endif
}

Some files were not shown because too many files have changed in this diff Show More