Code Restructuring to make mega-glest more standard

This commit is contained in:
Mark Vejvoda 2010-03-12 05:11:28 +00:00
parent b8082e83ce
commit 7cb4f99ec4
41 changed files with 768 additions and 431 deletions

1
mk/linux/data Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/data

View File

@ -1,4 +1,4 @@
; === Properties File ===
; === propertyMap File ===
AiLog=0
AiRedir=0
@ -24,13 +24,13 @@ FontConsole=-*-*-*-*-*-*-12-*-*-*-*-*-*-*
FontDisplay=-*-*-*-*-*-*-12-*-*-*-*-*-*-*
FontMenu=-*-*-*-*-*-*-12-*-*-*-*-*-*-*
Lang=english
MaxLights=1
NetworkConsistencyChecks=1
MaxLights=3
NetworkConsistencyChecks=0
PhotoMode=0
RefreshFrequency=75
ScreenHeight=768
ScreenWidth=1024
ServerIp=192.168.1.102
ScreenHeight=984
ScreenWidth=1680
ServerIp=200.200.200.200
ServerPort=6666
ShadowAlpha=0.2
ShadowFrameSkip=2
@ -38,10 +38,10 @@ ShadowTextureSize=512
Shadows=Projected
SoundStaticBuffers=16
SoundStreamingBuffers=4
SoundVolumeAmbient=80
SoundVolumeFx=80
SoundVolumeMusic=90
SoundVolumeAmbient=90
SoundVolumeFx=100
SoundVolumeMusic=0
StencilBits=0
Textures3D=1
UnitParticles=1
Windowed=0
Windowed=1

1
mk/linux/glest_game Symbolic link
View File

@ -0,0 +1 @@
../../source/glest_game

1
mk/linux/glest_map_editor Symbolic link
View File

@ -0,0 +1 @@
../../source/glest_map_editor

1
mk/linux/maps Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/maps

1
mk/linux/scenarios Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/scenarios

1
mk/linux/screenshots Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/screenshots

3
mk/linux/servers.ini Normal file
View File

@ -0,0 +1,3 @@
; === propertyMap File ===
Martino=192.168.1.100

1
mk/linux/shared_lib Symbolic link
View File

@ -0,0 +1 @@
../../source/shared_lib

1
mk/linux/techs Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/techs

1
mk/linux/tilesets Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/tilesets

1
mk/linux/tutorials Symbolic link
View File

@ -0,0 +1 @@
/home/softcoder/Code/glest/megaglest/data/glest_game/tutorials

0
mk/windoze/Glest.sln Normal file → Executable file
View File

BIN
mk/windoze/Glest.suo Normal file → Executable file

Binary file not shown.

0
mk/windoze/g3d_viewer.vcproj Normal file → Executable file
View File

0
mk/windoze/glest.ico Normal file → Executable file
View File

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

0
mk/windoze/glest.rc Normal file → Executable file
View File

0
mk/windoze/glest_editor.vcproj Normal file → Executable file
View File

0
mk/windoze/glest_game.vcproj Normal file → Executable file
View File

0
mk/windoze/shared_lib.vcproj Normal file → Executable file
View File

View File

@ -562,6 +562,14 @@ void Renderer::renderMouse3d(){
glColor4fv(color.ptr());
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, color.ptr());
const Model *buildingModel= building->getFirstStOfClass(scStop)->getAnimation();
//!!!
float rotateAmount = gui->getUnitTypeBuildRotation(building->getId());
if(rotateAmount >= 0) {
//if(Socket::enableDebugText) printf("In [%s::%s] rotate unit id = %d amount = %f\n",__FILE__,__FUNCTION__,building->getId(),rotateAmount);
glRotatef(rotateAmount, 0.f, 1.f, 0.f);
}
buildingModel->updateInterpolationData(0.f, false);
modelRenderer->render(buildingModel);
glDisable(GL_COLOR_MATERIAL);
@ -1350,6 +1358,14 @@ void Renderer::renderUnits(){
//render
const Model *model= unit->getCurrentModel();
model->updateInterpolationData(unit->getAnimProgress(), unit->isAlive());
//!!!
float rotateAmount = unit->getRotateAmount();
if(rotateAmount >= 0) {
//if(Socket::enableDebugText) printf("In [%s::%s] rotate unit id = %d amount = %f\n",__FILE__,__FUNCTION__,unit->getId(),rotateAmount);
glRotatef(rotateAmount, 0.f, 1.f, 0.f);
}
modelRenderer->render(model);
triangleCount+= model->getTriangleCount();
pointCount+= model->getVertexCount();
@ -2328,6 +2344,14 @@ void Renderer::renderUnitsFast(){
//render
const Model *model= unit->getCurrentModel();
model->updateInterpolationVertices(unit->getAnimProgress(), unit->isAlive());
//!!!
float rotateAmount = unit->getRotateAmount();
if(rotateAmount >= 0) {
//if(Socket::enableDebugText) printf("In [%s::%s] rotate unit id = %d amount = %f\n",__FILE__,__FUNCTION__,unit->getId(),rotateAmount);
glRotatef(rotateAmount, 0.f, 1.f, 0.f);
}
modelRenderer->render(model);
glPopMatrix();

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -121,7 +121,7 @@ public:
sCount
};
private:
private:
//config
int maxLights;
bool photoMode;
@ -134,7 +134,7 @@ private:
//game
const Game *game;
//misc
int triangleCount;
int pointCount;
@ -163,7 +163,7 @@ private:
int shadowMapFrame;
//water
float waterAnim;
float waterAnim;
private:
Renderer();
@ -184,7 +184,7 @@ public:
void end();
void endMenu();
void endGame();
//get
int getTriangleCount() const {return triangleCount;}
int getPointCount() const {return pointCount;}
@ -208,7 +208,7 @@ public:
void loadGameCameraMatrix();
void loadCameraMatrix(const Camera *camera);
void computeVisibleQuad();
//basic rendering
void renderMouse2d(int mouseX, int mouseY, int anim, float fade= 0.f);
void renderMouse3d();
@ -220,8 +220,8 @@ public:
void renderSelectionQuad();
void renderText(const string &text, const Font2D *font, float alpha, int x, int y, bool centered= false);
void renderText(const string &text, const Font2D *font, const Vec3f &color, int x, int y, bool centered= false);
void renderTextShadow(const string &text, const Font2D *font, int x, int y, bool centered= false);
void renderTextShadow(const string &text, const Font2D *font, int x, int y, bool centered= false);
//components
void renderLabel(const GraphicLabel *label);
void renderButton(const GraphicButton *button);
@ -238,7 +238,7 @@ public:
void renderMinimap();
void renderDisplay();
void renderMenuBackground(const MenuBackground *menuBackground);
//computing
bool computePosition(const Vec2i &screenPos, Vec2i &worldPos);
void computeSelected(Selection::UnitContainer &units, const Vec2i &posDown, const Vec2i &posUp);
@ -247,7 +247,7 @@ public:
string getGlInfo();
string getGlMoreInfo();
void autoConfig();
//clear
void clearBuffers();
void clearZBuffer();
@ -273,11 +273,11 @@ private:
Vec3f computeLightColor(float time);
Vec4f computeWaterColor(float waterLevel, float cellHeight);
void checkExtension(const string &extension, const string &msg);
//selection render
void renderObjectsFast();
void renderUnitsFast();
//gl requirements
void checkGlCaps();
void checkGlOptionalCaps();
@ -297,7 +297,7 @@ private:
void renderProgressBar(int size, int x, int y, Font2D *font);
void renderTile(const Vec2i &pos);
void renderQuad(int x, int y, int w, int h, const Texture2D *texture);
//static
static Texture2D::Filter strToTextureFilter(const string &s);
};

View File

@ -1,11 +1,12 @@
// ==============================================================
// ==============================================================
// This file is part of Glest (www.glest.org)
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -58,7 +59,7 @@ void Mouse3d::update(){
}
// ===============================
// class SelectionQuad
// class SelectionQuad
// ===============================
SelectionQuad::SelectionQuad(){
@ -87,6 +88,8 @@ void SelectionQuad::disable(){
//constructor
Gui::Gui(){
if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
posObjWorld= Vec2i(54, 14);
computeSelection= false;
validPosObjWorld= false;
@ -96,6 +99,8 @@ Gui::Gui(){
selectingPos= false;
selectingMeetingPoint= false;
activePos= invalidPos;
if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
}
void Gui::init(Game *game){
@ -110,23 +115,23 @@ void Gui::end(){
selection.clear();
}
// ==================== get ====================
// ==================== get ====================
const UnitType *Gui::getBuilding() const{
assert(selectingBuilding);
return choosenBuildingType;
}
// ==================== is ====================
// ==================== is ====================
bool Gui::isPlacingBuilding() const{
return isSelectingPos() && activeCommandType!=NULL && activeCommandType->getClass()==ccBuild;
}
// ==================== set ====================
// ==================== set ====================
void Gui::invalidatePosObjWorld(){
validPosObjWorld= false;
validPosObjWorld= false;
}
void Gui::setComputeSelectionFlag(){
@ -134,7 +139,7 @@ void Gui::setComputeSelectionFlag(){
}
// ==================== reset state ====================
// ==================== reset state ====================
void Gui::resetState(){
selectingBuilding= false;
@ -145,7 +150,7 @@ void Gui::resetState(){
activeCommandType= NULL;
}
// ==================== events ====================
// ==================== events ====================
void Gui::update(){
setComputeSelectionFlag();
@ -167,9 +172,14 @@ void Gui::mouseDownLeftDisplay(int x, int y){
if(posDisplay!= invalidPos){
if(selection.isComandable()){
if(selectingBuilding){
//if(Socket::enableDebugText) printf("In [%s::%s] selectingBuilding == true\n",__FILE__,__FUNCTION__);
mouseDownDisplayUnitBuild(posDisplay);
}
else{
//if(Socket::enableDebugText) printf("In [%s::%s] selectingBuilding == false\n",__FILE__,__FUNCTION__);
mouseDownDisplayUnitSkills(posDisplay);
}
}
@ -182,34 +192,55 @@ void Gui::mouseDownLeftDisplay(int x, int y){
}
void Gui::mouseMoveDisplay(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
computeInfoString(computePosDisplay(x, y));
}
void Gui::mouseDownLeftGraphics(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(selectingPos){
//if(Socket::enableDebugText) printf("In [%s::%s] selectingPos == true\n",__FILE__,__FUNCTION__);
//give standard orders
giveTwoClickOrders(x, y);
resetState();
}
//set meeting point
else if(selectingMeetingPoint){
if(Socket::enableDebugText) printf("In [%s::%s] selectingMeetingPoint == true\n",__FILE__,__FUNCTION__);
if(selection.isComandable()){
if(Socket::enableDebugText) printf("In [%s::%s] selection.isComandable() == true\n",__FILE__,__FUNCTION__);
Vec2i targetPos;
if(Renderer::getInstance().computePosition(Vec2i(x, y), targetPos)){
if(Socket::enableDebugText) printf("In [%s::%s] computePosition() == true\n",__FILE__,__FUNCTION__);
commander->trySetMeetingPoint(selection.getFrontUnit(), targetPos);
}
}
resetState();
}
else{
if(Socket::enableDebugText) printf("In [%s::%s] selectionQuad()\n",__FILE__,__FUNCTION__);
selectionQuad.setPosDown(Vec2i(x, y));
computeSelected(false);
}
computeDisplay();
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
}
void Gui::mouseDownRightGraphics(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(selectingPos || selectingMeetingPoint){
resetState();
}
@ -217,25 +248,31 @@ void Gui::mouseDownRightGraphics(int x, int y){
giveDefaultOrders(x, y);
}
computeDisplay();
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
}
void Gui::mouseUpLeftGraphics(int x, int y){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(!selectingPos && !selectingMeetingPoint){
if(selectionQuad.isEnabled()){
selectionQuad.setPosUp(Vec2i(x, y));
if(selection.isComandable() && random.randRange(0, 1)==0){
SoundRenderer::getInstance().playFx(
selection.getFrontUnit()->getType()->getSelectionSound(),
selection.getFrontUnit()->getCurrVector(),
selection.getFrontUnit()->getCurrVector(),
gameCamera->getPos());
}
selectionQuad.disable();
}
}
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
}
void Gui::mouseMoveGraphics(int x, int y){
//compute selection
if(selectionQuad.isEnabled()){
selectionQuad.setPosUp(Vec2i(x, y));
@ -247,6 +284,8 @@ void Gui::mouseMoveGraphics(int x, int y){
//compute position for building
if(isPlacingBuilding()){
//if(Socket::enableDebugText) printf("In [%s::%s] isPlacingBuilding() == true\n",__FILE__,__FUNCTION__);
validPosObjWorld= Renderer::getInstance().computePosition(Vec2i(x,y), posObjWorld);
}
@ -270,7 +309,20 @@ void Gui::groupKey(int groupIndex){
}
}
float Gui::getUnitTypeBuildRotation(int unitId) const {
float rotationValue = -1;
if(unitTypeBuildRotation.find(unitId) != unitTypeBuildRotation.end()) {
rotationValue = unitTypeBuildRotation.find(unitId)->second;
}
return rotationValue;
}
void Gui::hotKey(char key){
if(Socket::enableDebugText) printf("In [%s::%s] key = [%c]\n",__FILE__,__FUNCTION__,key);
if(key==' '){
centerCameraOnSelection();
}
@ -281,7 +333,27 @@ void Gui::hotKey(char key){
selectInterestingUnit(iutBuiltBuilding);
}
else if(key=='R'){
selectInterestingUnit(iutProducer);
//!!!
if(isPlacingBuilding()){
const UnitType *unitType = getBuilding();
float unitTypeRotation = getUnitTypeBuildRotation(unitType->getId());
if(Socket::enableDebugText) printf("In [%s::%s] unitType->getId() = %d unitTypeRotation = %f\n",__FILE__,__FUNCTION__,unitType->getId(),unitTypeRotation);
if(unitTypeRotation < 0) {
unitTypeRotation = 0;
}
unitTypeRotation += 90;
if(unitTypeRotation >= 360) {
unitTypeRotation = 0;
}
unitTypeBuildRotation[unitType->getId()] = unitTypeRotation;
if(Socket::enableDebugText) printf("In [%s::%s] unitType->getId() = %d NEW unitTypeRotation = %f\n",__FILE__,__FUNCTION__,unitType->getId(),unitTypeRotation);
}
else {
selectInterestingUnit(iutProducer);
}
}
else if(key=='D'){
selectInterestingUnit(iutDamaged);
@ -310,10 +382,10 @@ void Gui::onSelectionChanged(){
void Gui::giveOneClickOrders(){
CommandResult result;
if(selection.isUniform()){
result= commander->tryGiveCommand(&selection, activeCommandType);
result= commander->tryGiveCommand(&selection, activeCommandType);
}
else{
result= commander->tryGiveCommand(&selection, activeCommandClass);
result= commander->tryGiveCommand(&selection, activeCommandClass);
}
addOrdersResultToConsole(activeCommandClass, result);
activeCommandType= NULL;
@ -337,11 +409,11 @@ void Gui::giveDefaultOrders(int x, int y){
addOrdersResultToConsole(activeCommandClass, result);
if(result == crSuccess || result == crSomeFailed){
mouse3d.enable();
if(random.randRange(0, 1)==0){
SoundRenderer::getInstance().playFx(
selection.getFrontUnit()->getType()->getCommandSound(),
selection.getFrontUnit()->getCurrVector(),
selection.getFrontUnit()->getCurrVector(),
gameCamera->getPos());
}
}
@ -351,7 +423,7 @@ void Gui::giveDefaultOrders(int x, int y){
}
void Gui::giveTwoClickOrders(int x, int y){
CommandResult result;
//compute target
@ -365,26 +437,26 @@ void Gui::giveTwoClickOrders(int x, int y){
//give orders to the units of this faction
if(!selectingBuilding){
if(selection.isUniform()){
result= commander->tryGiveCommand(&selection, activeCommandType, targetPos, targetUnit);
result= commander->tryGiveCommand(&selection, activeCommandType, targetPos, targetUnit);
}
else{
result= commander->tryGiveCommand(&selection, activeCommandClass, targetPos, targetUnit);
result= commander->tryGiveCommand(&selection, activeCommandClass, targetPos, targetUnit);
}
}
else{
//selecting building
result= commander->tryGiveCommand( selection.getFrontUnit(), activeCommandType, posObjWorld, choosenBuildingType );
result= commander->tryGiveCommand( selection.getFrontUnit(), activeCommandType, posObjWorld, choosenBuildingType );
}
//graphical result
addOrdersResultToConsole(activeCommandClass, result);
if(result == crSuccess || result == crSomeFailed){
mouse3d.enable();
if(random.randRange(0, 1)==0){
SoundRenderer::getInstance().playFx(
selection.getFrontUnit()->getType()->getCommandSound(),
selection.getFrontUnit()->getCurrVector(),
selection.getFrontUnit()->getCurrVector(),
gameCamera->getPos());
}
}
@ -459,8 +531,8 @@ void Gui::mouseDownDisplayUnitSkills(int posDisplay){
if(!selection.isEmpty()){
if(posDisplay != cancelPos){
if(posDisplay!=meetingPointPos){
const Unit *unit= selection.getFrontUnit();
const Unit *unit= selection.getFrontUnit();
//uniform selection
if(selection.isUniform()){
if(unit->getFaction()->reqsOk(display.getCommandType(posDisplay))){
@ -510,7 +582,7 @@ void Gui::mouseDownDisplayUnitSkills(int posDisplay){
}
void Gui::mouseDownDisplayUnitBuild(int posDisplay){
int factionIndex= world->getThisFactionIndex();
int factionIndex= world->getThisFactionIndex();
if(posDisplay==cancelPos){
resetState();
@ -524,7 +596,7 @@ void Gui::mouseDownDisplayUnitBuild(int posDisplay){
assert(choosenBuildingType!=NULL);
selectingPos= true;;
activePos= posDisplay;
}
}
}
}
}
@ -561,11 +633,11 @@ void Gui::computeInfoString(int posDisplay){
display.setInfoText(lang.get("AlreadyUpgraded"));
}
else{
display.setInfoText(ct->getReqDesc());
display.setInfoText(ct->getReqDesc());
}
}
else{
display.setInfoText(ct->getReqDesc());
display.setInfoText(ct->getReqDesc());
}
}
}
@ -599,9 +671,9 @@ void Gui::computeDisplay(){
//init
display.clear();
// ================ PART 1 ================
//title, text and progress bar
if(selection.getCount()==1){
display.setTitle(selection.getFrontUnit()->getFullName());
@ -613,7 +685,7 @@ void Gui::computeDisplay(){
for(int i=0; i<selection.getCount(); ++i){
display.setUpImage(i, selection.getUnit(i)->getType()->getImage());
}
// ================ PART 2 ================
if(selectingPos || selectingMeetingPoint){
@ -643,7 +715,7 @@ void Gui::computeDisplay(){
int morphPos= 8;
for(int i=0; i<ut->getCommandTypeCount(); ++i){
int displayPos= i;
const CommandType *ct= ut->getCommandType(i);
const CommandType *ct= ut->getCommandType(i);
if(ct->getClass()==ccMorph){
displayPos= morphPos++;
}
@ -665,7 +737,7 @@ void Gui::computeDisplay(){
display.setCommandClass(lastCommand, cc);
lastCommand++;
}
}
}
}
}
else{
@ -687,9 +759,9 @@ void Gui::computeDisplay(){
int Gui::computePosDisplay(int x, int y){
int posDisplay= display.computeDownIndex(x, y);
if(posDisplay<0 || posDisplay>=Display::downCellCount){
posDisplay= invalidPos;
posDisplay= invalidPos;
}
else if(selection.isComandable()){
if(posDisplay!=cancelPos){
@ -697,7 +769,7 @@ int Gui::computePosDisplay(int x, int y){
if(!selectingBuilding){
//standard selection
if(display.getCommandClass(posDisplay)==ccNull && display.getCommandType(posDisplay)==NULL){
posDisplay= invalidPos;
posDisplay= invalidPos;
}
}
else{
@ -710,17 +782,17 @@ int Gui::computePosDisplay(int x, int y){
}
}
}
else{
else{
//check meeting point
if(!selection.isMeetable()){
posDisplay= invalidPos;
posDisplay= invalidPos;
}
}
}
else{
else{
//check cancel button
if(!selection.isCancelable()){
posDisplay= invalidPos;
posDisplay= invalidPos;
}
}
}
@ -732,11 +804,11 @@ int Gui::computePosDisplay(int x, int y){
}
void Gui::addOrdersResultToConsole(CommandClass cc, CommandResult result){
switch(result){
case crSuccess:
case crSuccess:
break;
case crFailReqs:
case crFailReqs:
switch(cc){
case ccBuild:
console->addStdMessage("BuildingNoReqs");
@ -766,7 +838,7 @@ void Gui::addOrdersResultToConsole(CommandClass cc, CommandResult result){
break;
}
break;
case crFailUndefined:
console->addStdMessage("InvalidOrder");
break;
@ -827,7 +899,7 @@ bool Gui::computeTarget(const Vec2i &screenPos, Vec2i &targetPos, const Unit *&t
Renderer &renderer= Renderer::getInstance();
renderer.computeSelected(uc, screenPos, screenPos);
validPosObjWorld= false;
if(!uc.empty()){
targetUnit= uc.front();
targetPos= targetUnit->getPos();

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -19,6 +19,7 @@
#include "console.h"
#include "selection.h"
#include "random.h"
#include <map>
using Shared::Util::Random;
@ -52,10 +53,10 @@ private:
public:
Mouse3d();
void enable();
void update();
bool isEnabled() const {return enabled;}
float getFade() const {return fade;}
int getRot() const {return rot;}
@ -84,7 +85,7 @@ public:
};
// =====================================================
// class Gui
// class Gui
//
/// In game GUI
// =====================================================
@ -106,7 +107,7 @@ private:
const World *world;
GameCamera *gameCamera;
Console *console;
//Positions
Vec2i posObjWorld; //world coords
bool validPosObjWorld;
@ -129,6 +130,8 @@ private:
bool selectingPos;
bool selectingMeetingPoint;
std::map<int, float> unitTypeBuildRotation;
public:
Gui();
void init(Game *game);
@ -137,7 +140,7 @@ public:
//get
Vec2i getPosObjWorld() const {return posObjWorld;}
const UnitType *getBuilding() const;
const Mouse3d *getMouse3d() const {return &mouse3d;}
const Display *getDisplay() const {return &display;}
const Selection *getSelection() const {return &selection;}
@ -171,8 +174,10 @@ public:
//misc
void onSelectionChanged();
float getUnitTypeBuildRotation(int unitId) const;
private:
//orders
void giveDefaultOrders(int x, int y);
void giveOneClickOrders();

0
source/glest_game/network/client_interface.cpp Normal file → Executable file
View File

View File

@ -3,12 +3,12 @@
//
// Copyright (C) 2001-2008 Marti<74>o Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
#include "faction.h"
#include "faction.h"
#include <cassert>
@ -24,6 +24,7 @@
#include "core_data.h"
#include "renderer.h"
#include "leak_dumper.h"
#include "socket.h"
using namespace Shared::Graphics;
using namespace Shared::Util;
@ -103,18 +104,27 @@ const int Unit::invalidId= -1;
// ============================ Constructor & destructor =============================
Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map){
Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map, float unitPlacementRotation) {
if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
Random random;
this->pos=pos;
this->type=type;
this->faction=faction;
this->map= map;
this->id= id;
level= NULL;
cellMap= NULL;
if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
setRotateAmount(unitPlacementRotation);
if(Socket::enableDebugText) printf("In [%s::%s] B unit id = %d [%s] rotate amount = %f\n",__FILE__,__FUNCTION__,getId(), getFullName().c_str(),unitPlacementRotation);
Config &config= Config::getInstance();
showUnitParticles= config.getBool("UnitParticles");
lastPos= pos;
progress= 0;
lastAnimProgress= 0;
@ -126,7 +136,7 @@ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map
deadCount= 0;
hp= type->getMaxHp()/20;
toBeUndertaken= false;
level= NULL;
highlight= 0.f;
meetingPos= pos;
alive= true;
@ -135,7 +145,7 @@ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map
random.init(id);
rot+= random.randRange(-5, 5);
rotation= rot;
lastRotation= rot;
targetRotation= rot;
@ -149,6 +159,8 @@ Unit::Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map
//starting skill
this->currSkill=getType()->getFirstStOfClass(scStop);
if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
}
Unit::~Unit(){
@ -163,6 +175,9 @@ Unit::~Unit(){
unitParticleSystems.pop_back();
}
stopDamageParticles();
delete [] cellMap;
cellMap = NULL;
}
// ====================================== get ======================================
@ -184,9 +199,8 @@ Vec2f Unit::getFloatCenteredPos() const{
}
Vec2i Unit::getCellPos() const{
if(type->hasCellMap()){
//find nearest pos to center that is free
Vec2i centeredPos= getCenteredPos();
float nearestDist= -1.f;
@ -194,7 +208,7 @@ Vec2i Unit::getCellPos() const{
for(int i=0; i<type->getSize(); ++i){
for(int j=0; j<type->getSize(); ++j){
if(type->getCellMapCell(i, j)){
if(getCellMapCell(i, j)){
Vec2i currPos= pos + Vec2i(i, j);
float dist= currPos.dist(centeredPos);
if(nearestDist==-1.f || dist<nearestDist){
@ -233,7 +247,7 @@ float Unit::getHpRatio() const{
}
float Unit::getEpRatio() const{
if(type->getMaxHp()==0){
if(type->getMaxHp()==0){
return 0.f;
}
else{
@ -256,11 +270,14 @@ const Level *Unit::getNextLevel() const{
}
string Unit::getFullName() const{
string str;
if(level!=NULL){
str+= level->getName() + " ";
string str="";
if(level != NULL){
str += (level->getName() + " ");
}
str+= type->getName();
if(type == NULL) {
throw runtime_error("type == NULL in Unit::getFullName()!");
}
str += type->getName();
return str;
}
@ -273,7 +290,7 @@ bool Unit::isOperative() const{
bool Unit::isBeingBuilt() const{
return currSkill->getClass()==scBeBuilt;
}
bool Unit::isBuilt() const{
return !isBeingBuilt();
}
@ -292,7 +309,7 @@ bool Unit::isDamaged() const{
bool Unit::isInteresting(InterestingUnitType iut) const{
switch(iut){
case iutIdleHarvester:
case iutIdleHarvester:
if(type->hasCommandClass(ccHarvest)){
if(!commands.empty()){
const CommandType *ct= commands.front()->getCommandType();
@ -303,11 +320,11 @@ bool Unit::isInteresting(InterestingUnitType iut) const{
}
return false;
case iutBuiltBuilding:
case iutBuiltBuilding:
return type->hasSkillClass(scBeBuilt) && isBuilt();
case iutProducer:
case iutProducer:
return type->hasSkillClass(scProduce);
case iutDamaged:
case iutDamaged:
return isDamaged();
case iutStore:
return type->getStoredResourceCount()>0;
@ -322,13 +339,13 @@ void Unit::setCurrSkill(const SkillType *currSkill){
if(currSkill->getClass()!=this->currSkill->getClass()){
animProgress= 0;
lastAnimProgress= 0;
while(!unitParticleSystems.empty()){
unitParticleSystems.back()->fade();
unitParticleSystems.pop_back();
}
}
if(showUnitParticles && (!currSkill->unitParticleSystemTypes.empty()) &&
if(showUnitParticles && (!currSkill->unitParticleSystemTypes.empty()) &&
(unitParticleSystems.empty()) ){
for(UnitParticleSystemTypes::const_iterator it= currSkill->unitParticleSystemTypes.begin(); it!=currSkill->unitParticleSystemTypes.end(); ++it){
UnitParticleSystem *ups;
@ -373,7 +390,7 @@ void Unit::setTargetPos(const Vec2i &targetPos){
targetRef= NULL;
this->targetPos= targetPos;
}
}
void Unit::setVisible(const bool visible){
for(UnitParticleSystems::iterator it= unitParticleSystems.begin(); it!=unitParticleSystems.end(); ++it){
@ -383,11 +400,11 @@ void Unit::setVisible(const bool visible){
(*it)->setVisible(visible);
}
}
// =============================== Render related ==================================
const Model *Unit::getCurrentModel() const{
return currSkill->getAnimation();
return currSkill->getAnimation();
}
Vec3f Unit::getCurrVector() const{
@ -399,11 +416,11 @@ Vec3f Unit::getCurrVectorFlat() const{
float y1= computeHeight(lastPos);
float y2= computeHeight(pos);
if(currSkill->getClass()==scMove){
v.x= lastPos.x + progress * (pos.x-lastPos.x);
v.z= lastPos.y + progress * (pos.y-lastPos.y);
v.y= y1+progress*(y2-y1);
v.y= y1+progress*(y2-y1);
}
else{
v.x= static_cast<float>(pos.x);
@ -421,7 +438,7 @@ Vec3f Unit::getCurrVectorFlat() const{
//any command
bool Unit::anyCommand() const{
return !commands.empty();
}
}
//return current command, assert that there is always one command
Command *Unit::getCurrCommand() const{
@ -435,7 +452,9 @@ unsigned int Unit::getCommandSize() const{
//give one command (clear, and push back)
CommandResult Unit::giveCommand(Command *command){
//if(Socket::enableDebugText) printf("In [%s::%s] START\n",__FILE__,__FUNCTION__);
if(command->getCommandType()->isQueuable()){
//cancel current command if it is not queuable
if(!commands.empty() && !commands.front()->getCommandType()->isQueuable()){
@ -447,13 +466,17 @@ CommandResult Unit::giveCommand(Command *command){
clearCommands();
unitPath.clear();
}
//if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
//check command
CommandResult result= checkCommand(command);
if(result==crSuccess){
applyCommand(command);
}
//if(Socket::enableDebugText) printf("In [%s::%s] B\n",__FILE__,__FUNCTION__);
//push back command
if(result== crSuccess){
commands.push_back(command);
@ -462,8 +485,10 @@ CommandResult Unit::giveCommand(Command *command){
delete command;
}
//if(Socket::enableDebugText) printf("In [%s::%s] END\n",__FILE__,__FUNCTION__);
return result;
}
}
//pop front (used when order is done)
CommandResult Unit::finishCommand(){
@ -483,7 +508,7 @@ CommandResult Unit::finishCommand(){
//to cancel a command
CommandResult Unit::cancelCommand(){
//is empty?
if(commands.empty()){
return crFailUndefined;
@ -514,13 +539,13 @@ void Unit::create(bool startingUnit){
void Unit::born(){
faction->addStore(type);
faction->applyStaticProduction(type);
faction->applyStaticProduction(type);
setCurrSkill(scStop);
hp= type->getMaxHp();
}
void Unit::kill(){
//no longer needs static resources
if(isBeingBuilt()){
faction->deApplyStaticConsumption(type);
@ -576,7 +601,7 @@ const CommandType *Unit::computeCommandType(const Vec2i &pos, const Unit *target
//attack enemies
if(!isAlly(targetUnit)){
commandType= type->getFirstAttackCommand(targetUnit->getCurrField());
}
}
//repair allies
else{
@ -609,12 +634,12 @@ bool Unit::update(){
//speed
int speed= currSkill->getTotalSpeed(&totalUpgrade);
//speed modifier
float diagonalFactor= 1.f;
float heightFactor= 1.f;
if(currSkill->getClass()==scMove){
//if moving in diagonal move slower
Vec2i dest= pos-lastPos;
if(abs(dest.x)+abs(dest.y) == 2){
@ -625,7 +650,7 @@ bool Unit::update(){
float heightDiff= map->getCell(pos)->getHeight() - map->getCell(targetPos)->getHeight();
heightFactor= clamp(1.f+heightDiff/5.f, 0.2f, 5.f);
}
//update progresses
lastAnimProgress= animProgress;
@ -668,7 +693,7 @@ bool Unit::update(){
}
//checks
if(progress>=1.f){
if(progress>=1.f){
lastRotation= targetRotation;
if(currSkill->getClass()!=scDie){
progress= 0.f;
@ -678,7 +703,7 @@ bool Unit::update(){
progress= 1.f;
deadCount++;
if(deadCount>=maxDeadCount){
toBeUndertaken= true;
toBeUndertaken= true;
return false;
}
}
@ -713,23 +738,23 @@ int Unit::update2(){
}
bool Unit::computeEp(){
//if not enough ep
if(ep-currSkill->getEpCost() < 0){
if(ep-currSkill->getEpCost() < 0){
return true;
}
//decrease ep
ep-= currSkill->getEpCost();
if(ep>getType()->getTotalMaxEp(&totalUpgrade)){
ep= getType()->getTotalMaxEp(&totalUpgrade);
ep= getType()->getTotalMaxEp(&totalUpgrade);
}
return false;
}
bool Unit::repair(){
//increase hp
hp+= getType()->getMaxHp()/type->getProductionTime() + 1;
if(hp>(getType()->getTotalMaxHp(&totalUpgrade))){
@ -749,7 +774,7 @@ bool Unit::decHp(int i){
if(hp==0){
return false;
}
hp-=i;
//startDamageParticles
@ -886,7 +911,7 @@ bool Unit::morph(const MorphCommandType *mct){
currField=morphUnitField;
computeTotalUpgrade();
map->putUnitCells(this, pos);
faction->applyDiscount(morphUnitType, mct->getDiscount());
faction->applyDiscount(morphUnitType, mct->getDiscount());
return true;
}
else{
@ -899,7 +924,7 @@ bool Unit::morph(const MorphCommandType *mct){
float Unit::computeHeight(const Vec2i &pos) const{
float height= map->getCell(pos)->getHeight();
if(currField==fAir){
height+= World::airHeight;
}
@ -931,7 +956,7 @@ void Unit::clearCommands(){
}
CommandResult Unit::checkCommand(Command *command) const{
//if not operative or has not command type => fail
if(!isOperative() || command->getUnit()==this || !getType()->hasCommandType(command->getCommandType())){
return crFailUndefined;
@ -966,13 +991,13 @@ CommandResult Unit::checkCommand(Command *command) const{
//upgrade command specific, check that upgrade is not upgraded
else if(command->getCommandType()->getClass()==ccUpgrade){
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
if(faction->getUpgradeManager()->isUpgradingOrUpgraded(uct->getProducedUpgrade())){
return crFailUndefined;
}
}
return crSuccess;
return crSuccess;
}
void Unit::applyCommand(Command *command){
@ -990,7 +1015,7 @@ void Unit::applyCommand(Command *command){
//upgrade command specific
else if(command->getCommandType()->getClass()==ccUpgrade){
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
faction->startUpgrade(uct->getProducedUpgrade());
}
}
@ -1003,7 +1028,7 @@ CommandResult Unit::undoCommand(Command *command){
faction->deApplyCosts(produced);
}
//return building cost if not already building it or dead
//return building cost if not already building it or dead
if(command->getCommandType()->getClass() == ccBuild){
if(currSkill->getClass()!=scBuild && currSkill->getClass()!=scDie){
faction->deApplyCosts(command->getUnitType());
@ -1034,7 +1059,7 @@ void Unit::stopDamageParticles(){
void Unit::startDamageParticles(){
//start additional particles
if( showUnitParticles && (!type->damageParticleSystemTypes.empty())
if( showUnitParticles && (!type->damageParticleSystemTypes.empty())
&& (damageParticleSystems.empty()) ){
for(UnitParticleSystemTypes::const_iterator it= type->damageParticleSystemTypes.begin(); it!=type->damageParticleSystemTypes.end(); ++it){
UnitParticleSystem *ups;
@ -1077,9 +1102,77 @@ void Unit::startDamageParticles(){
damageParticleSystems.push_back(ups);
Renderer::getInstance().manageParticleSystem(ups, rsGame);
}
}
}
bool Unit::getCellMapCell(int x, int y) const {
const UnitType *ut= getType();
if(ut != NULL && rotateAmount > 0) {
return cellMap[ut->getSize() * y + x];
}
else {
return ut->getCellMapCell(x,y);
}
}
void Unit::setRotateAmount(float value) {
rotateAmount = value;
if(Socket::enableDebugText) printf("In [%s::%s] unit id = %d [%s] rotate amount = %f\n",__FILE__,__FUNCTION__,getId(), getFullName().c_str(),rotateAmount);
const UnitType *ut= getType();
if(ut != NULL && ut->hasCellMap() == true) {
int matrixSize = ut->getSize();
if(rotateAmount > 0) {
delete [] cellMap;
cellMap = new bool[matrixSize * matrixSize];
for(int iRow = 0; iRow < matrixSize; ++iRow) {
for(int iCol = 0; iCol < matrixSize; ++iCol) {
bool getCellResult = ut->getCellMapCell(iCol, iRow);
if(Socket::enableDebugText) printf("In [%s::%s] [%d,%d] = %d\n",__FILE__,__FUNCTION__,iRow,iCol,getCellResult);
int newRow = 0;
int newCol = 0;
switch((int)rotateAmount)
{
case 90:
newRow = (matrixSize - iCol - 1);
newCol = iRow;
break;
case 180:
newRow = (matrixSize - iRow - 1);
newCol = (matrixSize - iCol - 1);
break;
case 270:
newRow = iCol;
newCol = (matrixSize - iRow - 1);
break;
}
if(Socket::enableDebugText) printf("In [%s::%s] ABOUT TO Transform to [%d,%d] = %d\n",__FILE__,__FUNCTION__,newRow,newCol,getCellResult);
// bool getCellMapCell(int x, int y) const {return cellMap[size*y+x];}
// cellMap[i*size+j]= row[j]=='0'? false: true;
cellMap[matrixSize * newRow + newCol] = getCellResult;
}
}
}
if(Socket::enableDebugText) printf("In [%s::%s] Transformed matrix below:\n",__FILE__,__FUNCTION__);
for(int iRow = 0; iRow < matrixSize; ++iRow) {
for(int iCol = 0; iCol < matrixSize; ++iCol) {
bool getCellResult = ut->getCellMapCell(iCol, iRow);
bool getCellResultRotated = getCellMapCell(iRow, iCol);
if(Socket::enableDebugText) printf("In [%s::%s] matrix [%d,%d] = %d, rotated = %d\n",__FILE__,__FUNCTION__,iRow,iCol,getCellResult,getCellResultRotated);
}
}
}
}
}}//end namespace

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Marti<74>o Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -73,7 +73,7 @@ public:
};
// =====================================================
// class UnitReference
// class UnitReference
// =====================================================
class UnitReference{
@ -89,7 +89,7 @@ public:
};
// =====================================================
// class UnitPath
// class UnitPath
//
/// Holds the next cells of a Unit movement
// =====================================================
@ -122,7 +122,7 @@ class Unit{
private:
typedef list<Command*> Commands;
typedef list<UnitObserver*> Observers;
typedef list<UnitParticleSystem*> UnitParticleSystems;
typedef list<UnitParticleSystem*> UnitParticleSystems;
public:
static const float speedDivider;
@ -141,7 +141,7 @@ private:
float lastAnimProgress; //between 0 and 1
float animProgress; //between 0 and 1
float highlight;
int progress2;
int progress2;
int kills;
UnitReference targetRef;
@ -152,18 +152,18 @@ private:
Vec2i pos;
Vec2i lastPos;
Vec2i targetPos; //absolute target pos
Vec2i targetPos; //absolute target pos
Vec3f targetVec;
Vec2i meetingPos;
float lastRotation; //in degrees
float targetRotation;
float rotation;
float targetRotation;
float rotation;
const UnitType *type;
const ResourceType *loadType;
const SkillType *currSkill;
bool toBeUndertaken;
bool alive;
bool showUnitParticles;
@ -179,9 +179,12 @@ private:
Observers observers;
UnitParticleSystems unitParticleSystems;
UnitParticleSystems damageParticleSystems;
float rotateAmount;
bool *cellMap;
public:
Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map);
Unit(int id, const Vec2i &pos, const UnitType *type, Faction *faction, Map *map, float unitPlacementRotation);
~Unit();
//queries
@ -200,7 +203,7 @@ public:
int getProductionPercent() const;
float getHpRatio() const;
float getEpRatio() const;
bool getToBeUndertaken() const {return toBeUndertaken;}
bool getToBeUndertaken() const {return toBeUndertaken;}
Vec2i getTargetPos() const {return targetPos;}
Vec3f getTargetVec() const {return targetVec;}
Field getTargetField() const {return targetField;}
@ -247,8 +250,8 @@ public:
void setLoadType(const ResourceType *loadType) {this->loadType= loadType;}
void setProgress2(int progress2) {this->progress2= progress2;}
void setPos(const Vec2i &pos);
void setTargetPos(const Vec2i &targetPos);
void setTarget(const Unit *unit);
void setTargetPos(const Vec2i &targetPos);
void setTarget(const Unit *unit);
void setTargetVec(const Vec3f &targetVec) {this->targetVec= targetVec;}
void setMeetingPos(const Vec2i &meetingPos) {this->meetingPos= meetingPos;}
void setVisible(const bool visible);
@ -257,12 +260,12 @@ public:
const Model *getCurrentModel() const;
Vec3f getCurrVector() const;
Vec3f getCurrVectorFlat() const;
//command related
bool anyCommand() const;
Command *getCurrCommand() const;
unsigned int getCommandSize() const;
CommandResult giveCommand(Command *command); //give a command
CommandResult giveCommand(Command *command); //give a command
CommandResult finishCommand(); //command finished
CommandResult cancelCommand(); //cancel canceled
@ -293,6 +296,10 @@ public:
bool morph(const MorphCommandType *mct);
CommandResult checkCommand(Command *command) const;
void applyCommand(Command *command);
void setRotateAmount(float value);
float getRotateAmount() { return rotateAmount; }
bool getCellMapCell(int x, int y) const;
private:
float computeHeight(const Vec2i &pos) const;

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -84,7 +84,7 @@ void StopCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
string StopCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str;
Lang &lang= Lang::getInstance();
str= name+"\n";
str+= lang.get("ReactionSpeed")+": "+ intToStr(stopSkillType->getSpeed())+"\n";
if(stopSkillType->getEpCost()!=0)
@ -132,7 +132,7 @@ void MoveCommandType::load(int id, const XmlNode *n, const string &dir, const Te
string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str;
Lang &lang= Lang::getInstance();
str= name+"\n";
str+= lang.get("WalkSpeed")+": "+ intToStr(moveSkillType->getSpeed());
if(totalUpgrade->getMoveSpeed()!=0){
@ -142,7 +142,7 @@ string MoveCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(moveSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(moveSkillType->getEpCost())+"\n";
}
return str;
}
@ -167,7 +167,7 @@ void AttackCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
void AttackCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut);
//move
string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue();
moveSkillType= static_cast<const MoveSkillType*>(ut.getSkillType(skillName, scMove));
@ -180,7 +180,7 @@ void AttackCommandType::load(int id, const XmlNode *n, const string &dir, const
string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str;
Lang &lang= Lang::getInstance();
str= name+"\n";
if(attackSkillType->getEpCost()!=0){
str+= lang.get("EpCost") + ": " + intToStr(attackSkillType->getEpCost()) + "\n";
@ -188,9 +188,9 @@ string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
//attack strength
str+= lang.get("AttackStrenght")+": ";
str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar());
str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar());
str+= "...";
str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar());
str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar());
if(totalUpgrade->getAttackStrength()!=0){
str+= "+"+intToStr(totalUpgrade->getAttackStrength());
}
@ -226,7 +226,7 @@ string AttackCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
str+= "+"+intToStr(totalUpgrade->getMoveSpeed());
}
str+="\n";
str+= lang.get("AttackSpeed")+": "+ intToStr(attackSkillType->getSpeed()) +"\n";
return str;
@ -272,12 +272,12 @@ string AttackStoppedCommandType::getDesc(const TotalUpgrade *totalUpgrade) const
if(attackSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(attackSkillType->getEpCost())+"\n";
}
//attack strength
str+= lang.get("AttackStrenght")+": ";
str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar());
str+= intToStr(attackSkillType->getAttackStrength()-attackSkillType->getAttackVar());
str+="...";
str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar());
str+= intToStr(attackSkillType->getAttackStrength()+attackSkillType->getAttackVar());
if(totalUpgrade->getAttackStrength()!=0)
str+= "+"+intToStr(totalUpgrade->getAttackStrength());
str+= " ("+ attackSkillType->getAttackType()->getName() +")";
@ -349,7 +349,7 @@ void BuildCommandType::load(int id, const XmlNode *n, const string &dir, const T
const XmlNode *buildingsNode= n->getChild("buildings");
for(int i=0; i<buildingsNode->getChildCount(); ++i){
const XmlNode *buildingNode= buildingsNode->getChild("building", i);
string name= buildingNode->getAttribute("name")->getRestrictedValue();
string name= buildingNode->getAttribute("name")->getRestrictedValue();
buildings.push_back(ft->getUnitType(name));
}
@ -383,13 +383,13 @@ void BuildCommandType::load(int id, const XmlNode *n, const string &dir, const T
string BuildCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str;
Lang &lang= Lang::getInstance();
str= name+"\n";
str+= lang.get("BuildSpeed")+": "+ intToStr(buildSkillType->getSpeed())+"\n";
if(buildSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(buildSkillType->getEpCost())+"\n";
}
return str;
}
@ -413,9 +413,9 @@ void HarvestCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
}
void HarvestCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut);
//move
string skillName= n->getChild("move-skill")->getAttribute("value")->getRestrictedValue();
moveSkillType= static_cast<const MoveSkillType*>(ut.getSkillType(skillName, scMove));
@ -444,7 +444,7 @@ void HarvestCommandType::load(int id, const XmlNode *n, const string &dir, const
}
string HarvestCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
Lang &lang= Lang::getInstance();
string str;
@ -490,7 +490,7 @@ void RepairCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
}
void RepairCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut);
//move
@ -518,7 +518,7 @@ string RepairCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(repairSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(repairSkillType->getEpCost())+"\n";
}
str+="\n"+lang.get("CanRepair")+":\n";
for(int i=0; i<repairableUnits.size(); ++i){
str+= (static_cast<const UnitType*>(repairableUnits[i]))->getName()+"\n";
@ -563,14 +563,14 @@ void ProduceCommandType::load(int id, const XmlNode *n, const string &dir, const
string skillName= n->getChild("produce-skill")->getAttribute("value")->getRestrictedValue();
produceSkillType= static_cast<const ProduceSkillType*>(ut.getSkillType(skillName, scProduce));
string producedUnitName= n->getChild("produced-unit")->getAttribute("name")->getRestrictedValue();
string producedUnitName= n->getChild("produced-unit")->getAttribute("name")->getRestrictedValue();
producedUnit= ft->getUnitType(producedUnitName);
}
string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str= name+"\n";
Lang &lang= Lang::getInstance();
//prod speed
str+= lang.get("ProductionSpeed")+": "+ intToStr(produceSkillType->getSpeed());
if(totalUpgrade->getProdSpeed()!=0){
@ -582,7 +582,7 @@ string ProduceCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(produceSkillType->getEpCost()!=0){
str+= lang.get("EpCost")+": "+intToStr(produceSkillType->getEpCost())+"\n";
}
str+= "\n" + getProducedUnit()->getReqDesc();
return str;
@ -616,16 +616,16 @@ void UpgradeCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
}
void UpgradeCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut);
//upgrade
string skillName= n->getChild("upgrade-skill")->getAttribute("value")->getRestrictedValue();
upgradeSkillType= static_cast<const UpgradeSkillType*>(ut.getSkillType(skillName, scUpgrade));
string producedUpgradeName= n->getChild("produced-upgrade")->getAttribute("name")->getRestrictedValue();
string producedUpgradeName= n->getChild("produced-upgrade")->getAttribute("name")->getRestrictedValue();
producedUpgrade= ft->getUpgradeType(producedUpgradeName);
}
string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
@ -636,7 +636,7 @@ string UpgradeCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
str+= lang.get("UpgradeSpeed")+": "+ intToStr(upgradeSkillType->getSpeed())+"\n";
if(upgradeSkillType->getEpCost()!=0)
str+= lang.get("EpCost")+": "+intToStr(upgradeSkillType->getEpCost())+"\n";
str+= "\n"+getProducedUpgrade()->getReqDesc();
return str;
@ -677,17 +677,17 @@ void MorphCommandType::load(int id, const XmlNode *n, const string &dir, const T
morphSkillType= static_cast<const MorphSkillType*>(ut.getSkillType(skillName, scMorph));
//morph unit
string morphUnitName= n->getChild("morph-unit")->getAttribute("name")->getRestrictedValue();
string morphUnitName= n->getChild("morph-unit")->getAttribute("name")->getRestrictedValue();
morphUnit= ft->getUnitType(morphUnitName);
//discount
discount= n->getChild("discount")->getAttribute("value")->getIntValue();
discount= n->getChild("discount")->getAttribute("value")->getIntValue();
}
string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str= name+"\n";
Lang &lang= Lang::getInstance();
//prod speed
str+= lang.get("MorphSpeed")+": "+ intToStr(morphSkillType->getSpeed())+"\n";
@ -700,7 +700,7 @@ string MorphCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
if(discount!=0){
str+= lang.get("Discount")+": "+intToStr(discount)+"%\n";
}
str+= "\n"+getProduced()->getReqDesc();
return str;
@ -719,6 +719,45 @@ const ProducibleType *MorphCommandType::getProduced() const{
return morphUnit;
}
// =====================================================
// class RotateUnitCommandType
// =====================================================
//varios
RotateUnitCommandType::RotateUnitCommandType(){
commandTypeClass= ccRotateUnit;
clicks= cOne;
}
void RotateUnitCommandType::update(UnitUpdater *unitUpdater, Unit *unit) const{
unitUpdater->updateStop(unit);
}
string RotateUnitCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{
string str;
Lang &lang= Lang::getInstance();
str= name+"\n";
//str+= lang.get("ReactionSpeed")+": "+ intToStr(stopSkillType->getSpeed())+"\n";
//if(stopSkillType->getEpCost()!=0)
// str+= lang.get("EpCost")+": "+intToStr(stopSkillType->getEpCost())+"\n";
return str;
}
string RotateUnitCommandType::toString() const{
Lang &lang= Lang::getInstance();
return lang.get("RotateUnit");
}
void RotateUnitCommandType::load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut){
CommandType::load(id, n, dir, tt, ft, ut);
//stop
//string skillName= n->getChild("stop-skill")->getAttribute("value")->getRestrictedValue();
//stopSkillType= static_cast<const StopSkillType*>(ut.getSkillType(skillName, scStop));
}
// =====================================================
// class CommandFactory
// =====================================================
@ -734,6 +773,7 @@ CommandTypeFactory::CommandTypeFactory(){
registerClass<ProduceCommandType>("produce");
registerClass<UpgradeCommandType>("upgrade");
registerClass<MorphCommandType>("morph");
registerClass<RotateUnitCommandType>("rotate_unit");
}
CommandTypeFactory &CommandTypeFactory::getInstance(){

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -41,6 +41,7 @@ enum CommandClass{
ccProduce,
ccUpgrade,
ccMorph,
ccRotateUnit,
ccCount,
ccNull
@ -75,13 +76,13 @@ public:
virtual bool isQueuable() const {return false;}
//get
CommandClass getClass() const;
Clicks getClicks() const {return clicks;}
int getId() const {return id;}
CommandClass getClass() const;
Clicks getClicks() const {return clicks;}
int getId() const {return id;}
};
// ===============================
// class StopCommandType
// class StopCommandType
// ===============================
class StopCommandType: public CommandType{
@ -101,7 +102,7 @@ public:
// ===============================
// class MoveCommandType
// class MoveCommandType
// ===============================
class MoveCommandType: public CommandType{
@ -121,7 +122,7 @@ public:
// ===============================
// class AttackCommandType
// class AttackCommandType
// ===============================
class AttackCommandType: public CommandType{
@ -142,7 +143,7 @@ public:
};
// =======================================
// class AttackStoppedCommandType
// class AttackStoppedCommandType
// =======================================
class AttackStoppedCommandType: public CommandType{
@ -164,7 +165,7 @@ public:
// ===============================
// class BuildCommandType
// class BuildCommandType
// ===============================
class BuildCommandType: public CommandType{
@ -194,7 +195,7 @@ public:
// ===============================
// class HarvestCommandType
// class HarvestCommandType
// ===============================
class HarvestCommandType: public CommandType{
@ -228,7 +229,7 @@ public:
// ===============================
// class RepairCommandType
// class RepairCommandType
// ===============================
class RepairCommandType: public CommandType{
@ -253,7 +254,7 @@ public:
// ===============================
// class ProduceCommandType
// class ProduceCommandType
// ===============================
class ProduceCommandType: public CommandType{
@ -278,7 +279,7 @@ public:
// ===============================
// class UpgradeCommandType
// class UpgradeCommandType
// ===============================
class UpgradeCommandType: public CommandType{
@ -302,7 +303,7 @@ public:
};
// ===============================
// class MorphCommandType
// class MorphCommandType
// ===============================
class MorphCommandType: public CommandType{
@ -327,7 +328,30 @@ public:
};
// ===============================
// class CommandFactory
// class BuildCommandType
// ===============================
class RotateUnitCommandType: public CommandType{
private:
float rotateAmount;
public:
RotateUnitCommandType();
virtual void update(UnitUpdater *unitUpdater, Unit *unit) const;
virtual void load(int id, const XmlNode *n, const string &dir, const TechTree *tt, const FactionType *ft, const UnitType &ut);
virtual string getDesc(const TotalUpgrade *totalUpgrade) const;
virtual string toString() const;
virtual bool isQueuable() const {return true;}
//get
const float getRotateAmount() const {return rotateAmount; }
void setRotateAmount(float value) { rotateAmount = value; }
};
// ===============================
// class CommandFactory
// ===============================
class CommandTypeFactory: public MultiFactory<CommandType>{

0
source/glest_game/types/skill_type.cpp Normal file → Executable file
View File

0
source/glest_game/types/skill_type.h Normal file → Executable file
View File

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Marti<74>o Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -25,6 +25,7 @@
#include "game_util.h"
#include "leak_dumper.h"
#include "unit_particle_type.h"
#include "socket.h"
using namespace Shared::Xml;
using namespace Shared::Graphics;
@ -33,7 +34,7 @@ using namespace Shared::Util;
namespace Glest{ namespace Game{
// ===============================
// class Level
// class Level
// ===============================
void Level::init(string name, int kills){
@ -45,11 +46,11 @@ void Level::init(string name, int kills){
// class UnitType
// =====================================================
// ===================== PUBLIC ========================
// ===================== PUBLIC ========================
const char *UnitType::propertyNames[]= {"burnable", "rotated_climb"};
// ==================== creation and loading ====================
// ==================== creation and loading ====================
UnitType::UnitType(){
@ -69,7 +70,7 @@ UnitType::UnitType(){
cellMap= NULL;
hpRegeneration= 0;
epRegeneration= 0;
}
}
UnitType::~UnitType(){
deleteValues(commandTypes.begin(), commandTypes.end());
@ -82,7 +83,7 @@ UnitType::~UnitType(){
delete damageParticleSystemTypes.back();
damageParticleSystemTypes.pop_back();
}
}
void UnitType::preLoad(const string &dir){
@ -90,7 +91,7 @@ void UnitType::preLoad(const string &dir){
}
void UnitType::load(int id,const string &dir, const TechTree *techTree, const FactionType *factionType, Checksum* checksum){
this->id= id;
string path;
@ -121,19 +122,19 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
//size
size= parametersNode->getChild("size")->getAttribute("value")->getIntValue();
//height
height= parametersNode->getChild("height")->getAttribute("value")->getIntValue();
//maxHp
maxHp= parametersNode->getChild("max-hp")->getAttribute("value")->getIntValue();
//hpRegeneration
hpRegeneration= parametersNode->getChild("max-hp")->getAttribute("regeneration")->getIntValue();
//maxEp
maxEp= parametersNode->getChild("max-ep")->getAttribute("value")->getIntValue();
if(maxEp!=0){
//wpRegeneration
epRegeneration= parametersNode->getChild("max-ep")->getAttribute("regeneration")->getIntValue();
@ -141,14 +142,14 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
//armor
armor= parametersNode->getChild("armor")->getAttribute("value")->getIntValue();
//armor type string
string armorTypeName= parametersNode->getChild("armor-type")->getAttribute("value")->getRestrictedValue();
armorType= techTree->getArmorType(armorTypeName);
//sight
sight= parametersNode->getChild("sight")->getAttribute("value")->getIntValue();
//prod time
productionTime= parametersNode->getChild("time")->getAttribute("value")->getIntValue();
@ -169,7 +170,20 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
for(int j=0; j<row.size(); ++j){
cellMap[i*size+j]= row[j]=='0'? false: true;
}
}
}
if(Socket::enableDebugText) printf("In [%s::%s] Original Unit cellmap matrix below [%s] [%s]:\n",__FILE__,__FUNCTION__,getName().c_str(),path.c_str());
for(int iRow = 0; iRow < size; ++iRow) {
const XmlNode *rowNode= cellMapNode->getChild("row", iRow);
string row= rowNode->getAttribute("value")->getRestrictedValue();
if(Socket::enableDebugText) printf("In [%s::%s] row = %s\n",__FILE__,__FUNCTION__,row.c_str());
for(int iCol = 0; iCol < size; ++iCol) {
bool getCellResult = getCellMapCell(iCol, iRow);
if(Socket::enableDebugText) printf("In [%s::%s] matrix [%d,%d] = %d\n",__FILE__,__FUNCTION__,iRow,iCol,getCellResult);
}
}
}
//levels
@ -236,7 +250,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
if(light){
lightColor.x= lightNode->getAttribute("red")->getFloatValue(0.f, 1.f);
lightColor.y= lightNode->getAttribute("green")->getFloatValue(0.f, 1.f);
lightColor.z= lightNode->getAttribute("blue")->getFloatValue(0.f, 1.f);
lightColor.z= lightNode->getAttribute("blue")->getFloatValue(0.f, 1.f);
}
//unit requirements
@ -333,7 +347,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
//commands
const XmlNode *commandsNode= unitNode->getChild("commands");
commandTypes.resize(commandsNode->getChildCount());
commandTypes.resize(commandsNode->getChildCount());
for(int i=0; i<commandTypes.size(); ++i){
const XmlNode *commandNode= commandsNode->getChild("command", i);
const XmlNode *typeNode= commandNode->getChild("type");
@ -342,7 +356,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
commandType->load(i, commandNode, dir, techTree, factionType, *this);
commandTypes[i]= commandType;
}
computeFirstStOfClass();
computeFirstCtOfClass();
@ -352,7 +366,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
if(getFirstStOfClass(scDie)==NULL){
throw runtime_error("Every unit must have at least one die skill: "+ path);
}
}
//Exception handling (conversions and so on);
catch(const exception &e){
@ -360,7 +374,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, const Fa
}
}
// ==================== get ====================
// ==================== get ====================
const CommandType *UnitType::getFirstCtOfClass(CommandClass commandClass) const{
return firstCommandTypeOfClass[commandClass];
@ -412,7 +426,7 @@ int UnitType::getStore(const ResourceType *rt) const{
return storedResources[i].getAmount();
}
}
return 0;
return 0;
}
const SkillType *UnitType::getSkillType(const string &skillName, SkillClass skillClass) const{
@ -429,7 +443,7 @@ const SkillType *UnitType::getSkillType(const string &skillName, SkillClass skil
throw runtime_error("No skill named \""+skillName+"\"");
}
// ==================== totals ====================
// ==================== totals ====================
int UnitType::getTotalMaxHp(const TotalUpgrade *totalUpgrade) const{
return maxHp + totalUpgrade->getMaxHp();
@ -447,10 +461,10 @@ int UnitType::getTotalSight(const TotalUpgrade *totalUpgrade) const{
return sight + totalUpgrade->getSight();
}
// ==================== has ====================
// ==================== has ====================
bool UnitType::hasSkillClass(SkillClass skillClass) const{
return firstSkillTypeOfClass[skillClass]!=NULL;
return firstSkillTypeOfClass[skillClass]!=NULL;
}
bool UnitType::hasCommandType(const CommandType *commandType) const{
@ -474,7 +488,7 @@ bool UnitType::hasSkillType(const SkillType *skillType) const{
return true;
}
}
return false;
return false;
}
bool UnitType::isOfClass(UnitClass uc) const{
@ -491,14 +505,14 @@ bool UnitType::isOfClass(UnitClass uc) const{
return false;
}
// ==================== PRIVATE ====================
// ==================== PRIVATE ====================
void UnitType::computeFirstStOfClass(){
for(int j= 0; j<scCount; ++j){
firstSkillTypeOfClass[j]= NULL;
for(int i= 0; i<skillTypes.size(); ++i){
if(skillTypes[i]->getClass()== SkillClass(j)){
firstSkillTypeOfClass[j]= skillTypes[i];
firstSkillTypeOfClass[j]= skillTypes[i];
break;
}
}
@ -510,7 +524,7 @@ void UnitType::computeFirstCtOfClass(){
firstCommandTypeOfClass[j]= NULL;
for(int i=0; i<commandTypes.size(); ++i){
if(commandTypes[i]->getClass()== CommandClass(j)){
firstCommandTypeOfClass[j]= commandTypes[i];
firstCommandTypeOfClass[j]= commandTypes[i];
break;
}
}

View File

@ -95,6 +95,7 @@ private:
int sight;
int size; //size in cells
int height;
float rotatedBuildPos;
//cellmap
bool *cellMap;
@ -181,6 +182,9 @@ public:
//find
const CommandType* findCommandTypeById(int id) const;
float getRotatedBuildPos() { return rotatedBuildPos; }
float setRotatedBuildPos(float value) { rotatedBuildPos = value; }
private:
void computeFirstStOfClass();
void computeFirstCtOfClass();

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -39,10 +39,10 @@ Cell::Cell(){
height= 0;
}
// ==================== misc ====================
// ==================== misc ====================
//returns if the cell is free
bool Cell::isFree(Field field) const{
bool Cell::isFree(Field field) const{
return getUnit(field)==NULL || getUnit(field)->isPutrefacting();
}
@ -83,7 +83,7 @@ void SurfaceCell::setVisible(int teamIndex, bool visible){
// class Map
// =====================================================
// ===================== PUBLIC ========================
// ===================== PUBLIC ========================
const int Map::cellScale= 2;
const int Map::mapScale= 2;
@ -103,7 +103,7 @@ Map::~Map(){
}
void Map::load(const string &path, TechTree *techTree, Tileset *tileset){
struct MapFileHeader{
int32 version;
int32 maxPlayers;
@ -155,14 +155,14 @@ void Map::load(const string &path, TechTree *techTree, Tileset *tileset){
//cells
cells= new Cell[w*h];
surfaceCells= new SurfaceCell[surfaceW*surfaceH];
//read heightmap
for(int j=0; j<surfaceH; ++j){
for(int i=0; i<surfaceW; ++i){
float32 alt;
fread(&alt, sizeof(float32), 1, f);
SurfaceCell *sc= getSurfaceCell(i, j);
sc->setVertex(Vec3f(i*mapScale, alt / heightFactor, j*mapScale));
sc->setVertex(Vec3f(i*mapScale, alt / heightFactor, j*mapScale));
}
}
@ -171,14 +171,14 @@ void Map::load(const string &path, TechTree *techTree, Tileset *tileset){
for(int i=0; i<surfaceW; ++i){
int8 surf;
fread(&surf, sizeof(int8), 1, f);
getSurfaceCell(i, j)->setSurfaceType(surf-1);
getSurfaceCell(i, j)->setSurfaceType(surf-1);
}
}
//read objects and resources
for(int j=0; j<h; j+= cellScale){
for(int i=0; i<w; i+= cellScale){
int8 objNumber;
fread(&objNumber, sizeof(int8), 1, f);
SurfaceCell *sc= getSurfaceCell(toSurfCoords(Vec2i(i, j)));
@ -224,7 +224,7 @@ void Map::init(){
}
// ==================== is ====================
// ==================== is ====================
bool Map::isInside(int x, int y) const{
return x>=0 && y>=0 && x<w && y<h;
@ -261,12 +261,12 @@ bool Map::isResourceNear(const Vec2i &pos, const ResourceType *rt, Vec2i &resour
}
// ==================== free cells ====================
// ==================== free cells ====================
bool Map::isFreeCell(const Vec2i &pos, Field field) const{
return
isInside(pos) &&
getCell(pos)->isFree(field) &&
return
isInside(pos) &&
getCell(pos)->isFree(field) &&
(field==fAir || getSurfaceCell(toSurfCoords(pos))->isFree()) &&
(field!=fLand || !getDeepSubmerged(getCell(pos)));
}
@ -286,7 +286,7 @@ bool Map::isFreeCellOrHasUnit(const Vec2i &pos, Field field, const Unit *unit) c
bool Map::isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const{
if(isInside(pos)){
if(isInside(pos)){
const SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos));
if(sc->isVisible(teamIndex)){
@ -298,7 +298,7 @@ bool Map::isAproxFreeCell(const Vec2i &pos, Field field, int teamIndex) const{
else{
return true;
}
}
}
return false;
}
@ -336,7 +336,7 @@ bool Map::isAproxFreeCells(const Vec2i &pos, int size, Field field, int teamInde
}
// ==================== unit placement ====================
// ==================== unit placement ====================
//checks if a unit can move from between 2 cells
bool Map::canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2) const{
@ -403,7 +403,7 @@ bool Map::aproxCanMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2) c
//put a units into the cells
void Map::putUnitCells(Unit *unit, const Vec2i &pos){
assert(unit!=NULL);
const UnitType *ut= unit->getType();
@ -411,19 +411,19 @@ void Map::putUnitCells(Unit *unit, const Vec2i &pos){
for(int j=0; j<ut->getSize(); ++j){
Vec2i currPos= pos + Vec2i(i, j);
assert(isInside(currPos));
if(!ut->hasCellMap() || ut->getCellMapCell(i, j)){
if(!ut->hasCellMap() || unit->getCellMapCell(i, j)){
assert(getCell(currPos)->getUnit(unit->getCurrField())==NULL);
getCell(currPos)->setUnit(unit->getCurrField(), unit);
}
}
}
}
unit->setPos(pos);
}
//removes a unit from cells
void Map::clearUnitCells(Unit *unit, const Vec2i &pos){
assert(unit!=NULL);
const UnitType *ut= unit->getType();
@ -431,19 +431,19 @@ void Map::clearUnitCells(Unit *unit, const Vec2i &pos){
for(int j=0; j<ut->getSize(); ++j){
Vec2i currPos= pos + Vec2i(i, j);
assert(isInside(currPos));
if(!ut->hasCellMap() || ut->getCellMapCell(i, j)){
if(!ut->hasCellMap() || unit->getCellMapCell(i, j)){
assert(getCell(currPos)->getUnit(unit->getCurrField())==unit);
getCell(currPos)->setUnit(unit->getCurrField(), NULL);
}
}
}
}
}
// ==================== misc ====================
// ==================== misc ====================
//returnis if unit is next to pos
bool Map::isNextTo(const Vec2i &pos, const Unit *unit) const{
for(int i=-1; i<=1; ++i){
for(int j=-1; j<=1; ++j){
if(isInside(pos.x+i, pos.y+j)) {
@ -477,15 +477,15 @@ void Map::prepareTerrain(const Unit *unit){
computeInterpolatedHeights();
}
// ==================== PRIVATE ====================
// ==================== PRIVATE ====================
// ==================== compute ====================
// ==================== compute ====================
void Map::flatternTerrain(const Unit *unit){
float refHeight= getSurfaceCell(toSurfCoords(unit->getCenteredPos()))->getHeight();
for(int i=-1; i<=unit->getType()->getSize(); ++i){
for(int j=-1; j<=unit->getType()->getSize(); ++j){
Vec2i pos= unit->getPos()+Vec2i(i, j);
Vec2i pos= unit->getPos()+Vec2i(i, j);
Cell *c= getCell(pos);
SurfaceCell *sc= getSurfaceCell(toSurfCoords(pos));
//we change height if pos is inside world, if its free or ocupied by the currenty building
@ -497,14 +497,14 @@ void Map::flatternTerrain(const Unit *unit){
}
//compute normals
void Map::computeNormals(){
void Map::computeNormals(){
//compute center normals
for(int i=1; i<surfaceW-1; ++i){
for(int j=1; j<surfaceH-1; ++j){
getSurfaceCell(i, j)->setNormal(
getSurfaceCell(i, j)->getVertex().normal(getSurfaceCell(i, j-1)->getVertex(),
getSurfaceCell(i+1, j)->getVertex(),
getSurfaceCell(i, j+1)->getVertex(),
getSurfaceCell(i, j)->getVertex().normal(getSurfaceCell(i, j-1)->getVertex(),
getSurfaceCell(i+1, j)->getVertex(),
getSurfaceCell(i, j+1)->getVertex(),
getSurfaceCell(i-1, j)->getVertex()));
}
}
@ -547,7 +547,7 @@ void Map::computeInterpolatedHeights(){
}
}
}
void Map::smoothSurface(){
@ -613,7 +613,7 @@ void Map::computeCellColors(){
}
}
// static
// static
string Map::getMapPath(const string &mapName) {
string mega = "maps/" + mapName + ".mgm";
string glest = "maps/" + mapName + ".gbm";
@ -639,9 +639,9 @@ PosCircularIterator::PosCircularIterator(const Map *map, const Vec2i &center, in
}
bool PosCircularIterator::next(){
//iterate while dont find a cell that is inside the world
//and at less or equal distance that the radius
//and at less or equal distance that the radius
do{
pos.x++;
if(pos.x > center.x+radius){
@ -653,7 +653,7 @@ bool PosCircularIterator::next(){
}
while(floor(pos.dist(center)) >= (radius+1) || !map->isInside(pos));
//while(!(pos.dist(center) <= radius && map->isInside(pos)));
return true;
}
@ -678,27 +678,27 @@ PosQuadIterator::PosQuadIterator(const Map *map, const Quad2i &quad, int step){
}
bool PosQuadIterator::next(){
do{
pos.x+= step;
if(pos.x > boundingRect.p[1].x){
pos.x= (boundingRect.p[0].x/step)*step;
pos.x= (boundingRect.p[0].x/step)*step;
pos.y+= step;
}
if(pos.y>boundingRect.p[1].y)
return false;
}
while(!quad.isInside(pos));
return true;
}
void PosQuadIterator::skipX(){
pos.x+= step;
}
}
const Vec2i &PosQuadIterator::getPos(){
return pos;
}
}}//end namespace

0
source/glest_game/world/map.h Normal file → Executable file
View File

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Marti<74>o Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -38,7 +38,7 @@ namespace Glest{ namespace Game{
// class UnitUpdater
// =====================================================
// ===================== PUBLIC ========================
// ===================== PUBLIC ========================
void UnitUpdater::init(Game *game){
@ -52,7 +52,7 @@ void UnitUpdater::init(Game *game){
}
// ==================== progress skills ====================
// ==================== progress skills ====================
//skill dependent actions
void UnitUpdater::updateUnit(Unit *unit){
@ -106,18 +106,18 @@ void UnitUpdater::updateUnit(Unit *unit){
unit->kill();
}
}
// ==================== progress commands ====================
// ==================== progress commands ====================
//VERY IMPORTANT: compute next state depending on the first order of the list
void UnitUpdater::updateUnitCommand(Unit *unit){
//if unis has command process it
if(unit->anyCommand()) {
unit->getCurrCommand()->getCommandType()->update(this, unit);
}
//if no commands stop and add stop command
if(!unit->anyCommand() && unit->isOperative()){
unit->setCurrSkill(scStop);
@ -127,21 +127,21 @@ void UnitUpdater::updateUnitCommand(Unit *unit){
}
}
// ==================== updateStop ====================
// ==================== updateStop ====================
void UnitUpdater::updateStop(Unit *unit){
Command *command= unit->getCurrCommand();
const StopCommandType *sct = static_cast<const StopCommandType*>(command->getCommandType());
Unit *sighted;
unit->setCurrSkill(sct->getStopSkillType());
//we can attack any unit => attack it
if(unit->getType()->hasSkillClass(scAttack)){
for(int i=0; i<unit->getType()->getCommandTypeCount(); ++i){
const CommandType *ct= unit->getType()->getCommandType(i);
//look for an attack skill
const AttackSkillType *ast= NULL;
if(ct->getClass()==ccAttack){
@ -154,7 +154,7 @@ void UnitUpdater::updateStop(Unit *unit){
//use it to attack
if(ast!=NULL){
if(attackableOnSight(unit, &sighted, ast)){
unit->giveCommand(new Command(ct, sighted->getPos()));
unit->giveCommand(new Command(ct, sighted->getPos()));
break;
}
}
@ -171,19 +171,19 @@ void UnitUpdater::updateStop(Unit *unit){
}
// ==================== updateMove ====================
// ==================== updateMove ====================
void UnitUpdater::updateMove(Unit *unit){
Command *command= unit->getCurrCommand();
const MoveCommandType *mct= static_cast<const MoveCommandType*>(command->getCommandType());
const MoveCommandType *mct= static_cast<const MoveCommandType*>(command->getCommandType());
Vec2i pos= command->getUnit()!=NULL? command->getUnit()->getCenteredPos(): command->getPos();
switch(pathFinder.findPath(unit, pos)){
case PathFinder::tsOnTheWay:
unit->setCurrSkill(mct->getMoveSkillType());
break;
break;
case PathFinder::tsBlocked:
if(unit->getPath()->isBlocked()){
@ -197,12 +197,12 @@ void UnitUpdater::updateMove(Unit *unit){
}
// ==================== updateAttack ====================
// ==================== updateAttack ====================
void UnitUpdater::updateAttack(Unit *unit){
Command *command= unit->getCurrCommand();
const AttackCommandType *act= static_cast<const AttackCommandType*>(command->getCommandType());
const AttackCommandType *act= static_cast<const AttackCommandType*>(command->getCommandType());
Unit *target= NULL;
//if found
@ -232,7 +232,7 @@ void UnitUpdater::updateAttack(Unit *unit){
switch (pathFinder.findPath(unit, pos)){
case PathFinder::tsOnTheWay:
unit->setCurrSkill(act->getMoveSkillType());
break;
break;
case PathFinder::tsBlocked:
if(unit->getPath()->isBlocked()){
unit->finishCommand();
@ -245,12 +245,12 @@ void UnitUpdater::updateAttack(Unit *unit){
}
// ==================== updateAttackStopped ====================
// ==================== updateAttackStopped ====================
void UnitUpdater::updateAttackStopped(Unit *unit){
Command *command= unit->getCurrCommand();
const AttackStoppedCommandType *asct= static_cast<const AttackStoppedCommandType*>(command->getCommandType());
const AttackStoppedCommandType *asct= static_cast<const AttackStoppedCommandType*>(command->getCommandType());
Unit *enemy;
if(attackableOnRange(unit, &enemy, asct->getAttackSkillType())){
@ -263,29 +263,32 @@ void UnitUpdater::updateAttackStopped(Unit *unit){
}
// ==================== updateBuild ====================
// ==================== updateBuild ====================
void UnitUpdater::updateBuild(Unit *unit){
Command *command= unit->getCurrCommand();
const BuildCommandType *bct= static_cast<const BuildCommandType*>(command->getCommandType());
const BuildCommandType *bct= static_cast<const BuildCommandType*>(command->getCommandType());
if(unit->getCurrSkill()->getClass() != scBuild) {
//if not building
const UnitType *ut= command->getUnitType();
switch (pathFinder.findPath(unit, command->getPos()-Vec2i(1))){
case PathFinder::tsOnTheWay:
unit->setCurrSkill(bct->getMoveSkillType());
break;
case PathFinder::tsArrived:
case PathFinder::tsArrived:
//if arrived destination
assert(command->getUnitType()!=NULL);
if(map->isFreeCells(command->getPos(), ut->getSize(), fLand)){
const UnitType *builtUnitType= command->getUnitType();
Unit *builtUnit= new Unit(world->getNextUnitId(), command->getPos(), builtUnitType, unit->getFaction(), world->getMap());
builtUnit->create();
//!!!
float unitRotation = gui->getUnitTypeBuildRotation(builtUnitType->getId());
Unit *builtUnit= new Unit(world->getNextUnitId(), command->getPos(), builtUnitType, unit->getFaction(), world->getMap(),unitRotation);
builtUnit->create();
if(!builtUnitType->hasSkillClass(scBeBuilt)){
throw runtime_error("Unit " + builtUnitType->getName() + "has no be_built skill");
@ -296,14 +299,33 @@ void UnitUpdater::updateBuild(Unit *unit){
unit->setTarget(builtUnit);
map->prepareTerrain(builtUnit);
command->setUnit(builtUnit);
//play start sound
if(unit->getFactionIndex()==world->getThisFactionIndex()){
SoundRenderer::getInstance().playFx(
bct->getStartSound(),
unit->getCurrVector(),
unit->getCurrVector(),
gameCamera->getPos());
}
//!!!
/*
if(unitRotation > 0) {
if(Socket::enableDebugText) printf("In [%s::%s] before sending ccRotateUnit...\n",__FILE__,__FUNCTION__);
RotateUnitCommandType *rotateCmdType = new RotateUnitCommandType();
rotateCmdType->setRotateAmount(unitRotation);
Command *rotateUnitCmd = new Command(rotateCmdType);
rotateUnitCmd->setUnit(builtUnit);
if(Socket::enableDebugText) printf("In [%s::%s] in sending ccRotateUnit...\n",__FILE__,__FUNCTION__);
builtUnit->giveCommand(rotateUnitCmd);
if(Socket::enableDebugText) printf("In [%s::%s] after sending ccRotateUnit...\n",__FILE__,__FUNCTION__);
}
*/
}
else{
//if there are no free cells
@ -325,7 +347,7 @@ void UnitUpdater::updateBuild(Unit *unit){
else{
//if building
Unit *builtUnit= map->getCell(unit->getTargetPos())->getUnit(fLand);
//if u is killed while building then u==NULL;
if(builtUnit!=NULL && builtUnit!=command->getUnit()){
unit->setCurrSkill(scStop);
@ -343,10 +365,10 @@ void UnitUpdater::updateBuild(Unit *unit){
if(unit->getFactionIndex()==world->getThisFactionIndex()){
SoundRenderer::getInstance().playFx(
bct->getBuiltSound(),
unit->getCurrVector(),
unit->getCurrVector(),
gameCamera->getPos());
}
}
}
}
}
@ -354,11 +376,11 @@ void UnitUpdater::updateBuild(Unit *unit){
// ==================== updateHarvest ====================
void UnitUpdater::updateHarvest(Unit *unit){
Command *command= unit->getCurrCommand();
const HarvestCommandType *hct= static_cast<const HarvestCommandType*>(command->getCommandType());
const HarvestCommandType *hct= static_cast<const HarvestCommandType*>(command->getCommandType());
Vec2i targetPos;
if(unit->getCurrSkill()->getClass() != scHarvest) {
//if not working
if(unit->getLoadCount()==0){
@ -366,7 +388,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
Resource *r= map->getSurfaceCell(Map::toSurfCoords(command->getPos()))->getResource();
if(r!=NULL && hct->canHarvest(r->getType())){
//if can harvest dest. pos
if(unit->getPos().dist(command->getPos())<harvestDistance &&
if(unit->getPos().dist(command->getPos())<harvestDistance &&
map->isResourceNear(unit->getPos(), r->getType(), targetPos)) {
//if it finds resources it starts harvesting
unit->setCurrSkill(hct->getHarvestSkillType());
@ -395,7 +417,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
}
else{
//if loaded, return to store
Unit *store= world->nearestStore(unit->getPos(), unit->getFaction()->getIndex(), unit->getLoadType());
Unit *store= world->nearestStore(unit->getPos(), unit->getFaction()->getIndex(), unit->getLoadType());
if(store!=NULL){
switch(pathFinder.findPath(unit, store->getCenteredPos())){
case PathFinder::tsOnTheWay:
@ -404,10 +426,10 @@ void UnitUpdater::updateHarvest(Unit *unit){
default:
break;
}
//world->changePosCells(unit,unit->getPos()+unit->getDest());
if(map->isNextTo(unit->getPos(), store)){
//update resources
int resourceAmount= unit->getLoadCount();
if(unit->getFaction()->getCpuUltraControl()){
@ -431,7 +453,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
}
}
}
else{
else{
//if working
SurfaceCell *sc= map->getSurfaceCell(Map::toSurfCoords(unit->getTargetPos()));
Resource *r= sc->getResource();
@ -441,7 +463,7 @@ void UnitUpdater::updateHarvest(Unit *unit){
if(unit->getProgress2()>=hct->getHitsPerUnit()){
unit->setProgress2(0);
unit->setLoadCount(unit->getLoadCount()+1);
//if resource exausted, then delete it and stop
if(r->decAmount(1)){
sc->deleteResource();
@ -466,17 +488,17 @@ void UnitUpdater::updateHarvest(Unit *unit){
// ==================== updateRepair ====================
void UnitUpdater::updateRepair(Unit *unit){
Command *command= unit->getCurrCommand();
const RepairCommandType *rct= static_cast<const RepairCommandType*>(command->getCommandType());
Unit *repaired= map->getCell(command->getPos())->getUnit(fLand);
bool nextToRepaired= repaired!=NULL && map->isNextTo(unit->getPos(), repaired);
if(unit->getCurrSkill()->getClass()!=scRepair || !nextToRepaired){
//if not repairing
if(repaired!=NULL && rct->isRepairableUnitType(repaired->getType()) && repaired->isDamaged()){
if(nextToRepaired){
unit->setTarget(repaired);
unit->setCurrSkill(rct->getRepairSkillType());
@ -485,7 +507,7 @@ void UnitUpdater::updateRepair(Unit *unit){
switch(pathFinder.findPath(unit, command->getPos())){
case PathFinder::tsOnTheWay:
unit->setCurrSkill(rct->getMoveSkillType());
break;
break;
case PathFinder::tsBlocked:
if(unit->getPath()->isBlocked()){
unit->finishCommand();
@ -521,7 +543,7 @@ void UnitUpdater::updateRepair(Unit *unit){
// ==================== updateProduce ====================
void UnitUpdater::updateProduce(Unit *unit){
Command *command= unit->getCurrCommand();
const ProduceCommandType *pct= static_cast<const ProduceCommandType*>(command->getCommandType());
Unit *produced;
@ -535,8 +557,11 @@ void UnitUpdater::updateProduce(Unit *unit){
if(unit->getProgress2()>pct->getProduced()->getProductionTime()){
unit->finishCommand();
unit->setCurrSkill(scStop);
produced= new Unit(world->getNextUnitId(), Vec2i(0), pct->getProducedUnit(), unit->getFaction(), world->getMap());
//!!!
float unitRotation = gui->getUnitTypeBuildRotation(pct->getProducedUnit()->getId());
produced= new Unit(world->getNextUnitId(), Vec2i(0), pct->getProducedUnit(), unit->getFaction(), world->getMap(),unitRotation);
//place unit creates the unit
if(!world->placeUnit(unit->getCenteredPos(), 10, produced)){
delete produced;
@ -559,16 +584,16 @@ void UnitUpdater::updateProduce(Unit *unit){
// ==================== updateUpgrade ====================
void UnitUpdater::updateUpgrade(Unit *unit){
Command *command= unit->getCurrCommand();
const UpgradeCommandType *uct= static_cast<const UpgradeCommandType*>(command->getCommandType());
if(unit->getCurrSkill()->getClass()!=scUpgrade){
//if not producing
unit->setCurrSkill(uct->getUpgradeSkillType());
}
else{
//if producing
//if producing
unit->update2();
if(unit->getProgress2()>uct->getProduced()->getProductionTime()){
unit->finishCommand();
@ -581,10 +606,10 @@ void UnitUpdater::updateUpgrade(Unit *unit){
// ==================== updateMorph ====================
void UnitUpdater::updateMorph(Unit *unit){
Command *command= unit->getCurrCommand();
const MorphCommandType *mct= static_cast<const MorphCommandType*>(command->getCommandType());
if(unit->getCurrSkill()->getClass()!=scMorph){
//if not morphing, check space
if(map->isFreeCellsOrHasUnit(unit->getPos(), mct->getMorphUnit()->getSize(), unit->getCurrField(), unit)){
@ -600,7 +625,7 @@ void UnitUpdater::updateMorph(Unit *unit){
else{
unit->update2();
if(unit->getProgress2()>mct->getProduced()->getProductionTime()){
//finish the command
if(unit->morph(mct)){
unit->finishCommand();
@ -616,29 +641,29 @@ void UnitUpdater::updateMorph(Unit *unit){
}
}
unit->setCurrSkill(scStop);
}
}
}
// ==================== PRIVATE ====================
// ==================== PRIVATE ====================
// ==================== attack ====================
// ==================== attack ====================
void UnitUpdater::hit(Unit *attacker){
hit(attacker, static_cast<const AttackSkillType*>(attacker->getCurrSkill()), attacker->getTargetPos(), attacker->getTargetField());
}
void UnitUpdater::hit(Unit *attacker, const AttackSkillType* ast, const Vec2i &targetPos, Field targetField){
//hit attack positions
if(ast->getSplash()){
PosCircularIterator pci(map, targetPos, ast->getSplashRadius());
while(pci.next()){
Unit *attacked= map->getCell(pci.getPos())->getUnit(targetField);
if(attacked!=NULL){
if(ast->getSplashDamageAll()
|| !attacker->isAlly(attacked)
if(ast->getSplashDamageAll()
|| !attacker->isAlly(attacked)
|| ( targetPos.x==pci.getPos().x && targetPos.y==pci.getPos().y )){
damage(attacker, ast, attacked, pci.getPos().dist(attacker->getTargetPos()));
}
@ -661,7 +686,7 @@ void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attac
int var= ast->getAttackVar();
int armor= attacked->getType()->getTotalArmor(attacked->getTotalUpgrade());
float damageMultiplier= world->getTechTree()->getDamageMultiplier(ast->getAttackType(), attacked->getType()->getArmorType());
//compute damage
damage+= random.randRange(-var, var);
damage/= distance+1;
@ -676,19 +701,19 @@ void UnitUpdater::damage(Unit *attacker, const AttackSkillType* ast, Unit *attac
world->getStats()->kill(attacker->getFactionIndex(), attacked->getFactionIndex());
attacker->incKills();
scriptManager->onUnitDied(attacked);
}
}
}
void UnitUpdater::startAttackParticleSystem(Unit *unit){
Renderer &renderer= Renderer::getInstance();
ProjectileParticleSystem *psProj = 0;
SplashParticleSystem *psSplash;
const AttackSkillType *ast= static_cast<const AttackSkillType*>(unit->getCurrSkill());
ParticleSystemTypeProjectile *pstProj= ast->getProjParticleType();
ParticleSystemTypeSplash *pstSplash= ast->getSplashParticleType();
Vec3f startPos= unit->getCurrVector();
Vec3f endPos= unit->getTargetVec();
@ -699,7 +724,7 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
//projectile
if(pstProj!=NULL){
psProj= pstProj->create();
psProj= pstProj->create();
psProj->setPath(startPos, endPos);
psProj->setObserver(new ParticleDamager(unit, this, gameCamera));
psProj->setVisible(visible);
@ -723,12 +748,12 @@ void UnitUpdater::startAttackParticleSystem(Unit *unit){
}
}
// ==================== misc ====================
// ==================== misc ====================
//looks for a resource of type rt, if rt==NULL looks for any
//resource the unit can harvest
bool UnitUpdater::searchForResource(Unit *unit, const HarvestCommandType *hct){
Vec2i pos= unit->getCurrCommand()->getPos();
for(int radius= 0; radius<maxResSearchRadius; radius++){
@ -766,7 +791,7 @@ bool UnitUpdater::attackableOnRange(const Unit *unit, Unit **rangedPtr, const At
//if the unit has any enemy on range
bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, const AttackSkillType *ast){
vector<Unit*> enemies;
//we check command target
@ -786,22 +811,22 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, con
//nearby cells
for(int i=center.x-range; i<center.x+range+size; ++i){
for(int j=center.y-range; j<center.y+range+size; ++j){
//cells insede map and in range
if(map->isInside(i, j) && floor(floatCenter.dist(Vec2f(i, j))) <= (range+1)){
//all fields
for(int k=0; k<fieldCount; k++){
Field f= static_cast<Field>(k);
//check field
if((ast==NULL || ast->getAttackField(f))){
Unit *possibleEnemy= map->getCell(i, j)->getUnit(f);
//check enemy
if(possibleEnemy!=NULL && possibleEnemy->isAlive()){
if((!unit->isAlly(possibleEnemy) && commandTarget==NULL) || commandTarget==possibleEnemy){
enemies.push_back(possibleEnemy);
if((!unit->isAlly(possibleEnemy) && commandTarget==NULL) || commandTarget==possibleEnemy){
enemies.push_back(possibleEnemy);
}
}
}
@ -813,7 +838,7 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, con
//attack enemies that can attack first
for(int i=0; i<enemies.size(); ++i){
if(enemies[i]->getType()->hasSkillClass(scAttack)){
*rangedPtr= enemies[i];
*rangedPtr= enemies[i];
return true;
}
}
@ -823,7 +848,7 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, con
*rangedPtr= enemies.front();
return true;
}
return false;
}
@ -842,11 +867,11 @@ ParticleDamager::ParticleDamager(Unit *attacker, UnitUpdater *unitUpdater, const
void ParticleDamager::update(ParticleSystem *particleSystem){
Unit *attacker= attackerRef.getUnit();
if(attacker!=NULL){
unitUpdater->hit(attacker, ast, targetPos, targetField);
//play sound
StaticSound *projSound= ast->getProjSound();
if(particleSystem->getVisible() && projSound!=NULL){

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -14,8 +14,8 @@
#include <algorithm>
#include <cassert>
#include "config.h"
#include "faction.h"
#include "config.h"
#include "faction.h"
#include "unit.h"
#include "game.h"
#include "logger.h"
@ -34,7 +34,7 @@ namespace Glest{ namespace Game{
const float World::airHeight= 5.f;
// ===================== PUBLIC ========================
// ===================== PUBLIC ========================
World::World(){
Config &config= Config::getInstance();
@ -47,6 +47,7 @@ World::World(){
nextUnitId= 0;
scriptManager= NULL;
this->game = NULL;
}
void World::end(){
@ -61,7 +62,8 @@ void World::end(){
// ========================== init ===============================================
void World::init(Game *game, bool createUnits){
this->game = game;
scriptManager= game->getScriptManager();
unitUpdater.init(game);
@ -72,7 +74,7 @@ void World::init(Game *game, bool createUnits){
initSplattedTextures();
//minimap must be init after sum computation
initMinimap();
initMinimap();
if(createUnits){
initUnits();
}
@ -103,7 +105,7 @@ void World::loadScenario(const string &path, Checksum *checksum){
scenario.load(path);
}
// ==================== misc ====================
// ==================== misc ====================
void World::update(){
@ -150,7 +152,7 @@ void World::update(){
minimap.updateFowTex(clamp(fogFactor, 0.f, 1.f));
}
//tick
//tick
if(frameCount%GameConstants::updateFps==0){
computeFow();
tick();
@ -172,16 +174,16 @@ void World::tick(){
//compute resources balance
for(int k=0; k<getFactionCount(); ++k){
Faction *faction= getFaction(k);
//for each resource
for(int i=0; i<techTree.getResourceTypeCount(); ++i){
const ResourceType *rt= techTree.getResourceType(i);
//if consumable
if(rt->getClass()==rcConsumable){
int balance= 0;
for(int j=0; j<faction->getUnitCount(); ++j){
//if unit operative and has this cost
const Unit *u= faction->getUnit(j);
if(u->isOperative()){
@ -200,10 +202,10 @@ void World::tick(){
Unit* World::findUnitById(int id){
for(int i= 0; i<getFactionCount(); ++i){
Faction* faction= getFaction(i);
for(int j= 0; j<faction->getUnitCount(); ++j){
Unit* unit= faction->getUnit(j);
if(unit->getId()==id){
return unit;
}
@ -215,7 +217,7 @@ Unit* World::findUnitById(int id){
const UnitType* World::findUnitTypeById(const FactionType* factionType, int id){
for(int i= 0; i<factionType->getUnitTypeCount(); ++i){
const UnitType* unitType= factionType->getUnitType(i);
if(unitType->getId()==id){
return unitType;
}
@ -254,8 +256,8 @@ bool World::placeUnit(const Vec2i &startLoc, int radius, Unit *unit, bool spacia
//clears a unit old position from map and places new position
void World::moveUnitCells(Unit *unit){
Vec2i newPos= unit->getTargetPos();
Vec2i newPos= unit->getTargetPos();
//newPos must be free or the same pos as current
assert(map.getCell(unit->getPos())->getUnit(unit->getCurrField())==unit || map.isFreeCell(newPos, unit->getCurrField()));
map.clearUnitCells(unit, unit->getPos());
@ -290,16 +292,16 @@ Unit *World::nearestStore(const Vec2i &pos, int factionIndex, const ResourceType
bool World::toRenderUnit(const Unit *unit, const Quad2i &visibleQuad) const{
//a unit is rendered if it is in a visible cell or is attacking a unit in a visible cell
return
return
visibleQuad.isInside(unit->getPos()) &&
toRenderUnit(unit);
}
bool World::toRenderUnit(const Unit *unit) const{
return
map.getSurfaceCell(Map::toSurfCoords(unit->getCenteredPos()))->isVisible(thisTeamIndex) ||
(unit->getCurrSkill()->getClass()==scAttack &&
return
map.getSurfaceCell(Map::toSurfCoords(unit->getCenteredPos()))->isVisible(thisTeamIndex) ||
(unit->getCurrSkill()->getClass()==scAttack &&
map.getSurfaceCell(Map::toSurfCoords(unit->getTargetPos()))->isVisible(thisTeamIndex));
}
@ -309,14 +311,20 @@ void World::createUnit(const string &unitName, int factionIndex, const Vec2i &po
const FactionType* ft= faction->getType();
const UnitType* ut= ft->getUnitType(unitName);
Unit* unit= new Unit(getNextUnitId(), pos, ut, faction, &map);
//!!!
if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
float unitRotation = game->getGui()->getUnitTypeBuildRotation(ut->getId());
if(Socket::enableDebugText) printf("In [%s::%s] B\n",__FILE__,__FUNCTION__);
Unit* unit= new Unit(getNextUnitId(), pos, ut, faction, &map, unitRotation);
if(placeUnit(pos, generationArea, unit, true)){
unit->create(true);
unit->born();
scriptManager->onUnitCreated(unit);
}
else{
throw runtime_error("Unit cant be placed");
throw runtime_error("Unit cant be placed");
}
}
else
@ -343,7 +351,7 @@ void World::givePositionCommand(int unitId, const string &commandName, const Vec
CommandClass cc;
if(commandName=="move"){
cc= ccMove;
cc= ccMove;
}
else if(commandName=="attack"){
cc= ccAttack;
@ -351,7 +359,7 @@ void World::givePositionCommand(int unitId, const string &commandName, const Vec
else{
throw runtime_error("Invalid position commmand: " + commandName);
}
unit->giveCommand(new Command( unit->getType()->getFirstCtOfClass(cc), pos ));
}
}
@ -360,7 +368,7 @@ void World::giveProductionCommand(int unitId, const string &producedName){
Unit *unit= findUnitById(unitId);
if(unit!=NULL){
const UnitType *ut= unit->getType();
//Search for a command that can produce the unit
for(int i= 0; i<ut->getCommandTypeCount(); ++i){
const CommandType* ct= ut->getCommandType(i);
@ -379,7 +387,7 @@ void World::giveUpgradeCommand(int unitId, const string &upgradeName){
Unit *unit= findUnitById(unitId);
if(unit!=NULL){
const UnitType *ut= unit->getType();
//Search for a command that can produce the unit
for(int i= 0; i<ut->getCommandTypeCount(); ++i){
const CommandType* ct= ut->getCommandType(i);
@ -438,7 +446,7 @@ int World::getUnitCount(int factionIndex){
if(factionIndex<factions.size()){
Faction* faction= &factions[factionIndex];
int count= 0;
for(int i= 0; i<faction->getUnitCount(); ++i){
const Unit* unit= faction->getUnit(i);
if(unit->isAlive()){
@ -457,7 +465,7 @@ int World::getUnitCountOfType(int factionIndex, const string &typeName){
if(factionIndex<factions.size()){
Faction* faction= &factions[factionIndex];
int count= 0;
for(int i= 0; i< faction->getUnitCount(); ++i){
const Unit* unit= faction->getUnit(i);
if(unit->isAlive() && unit->getType()->getName()==typeName){
@ -472,9 +480,9 @@ int World::getUnitCountOfType(int factionIndex, const string &typeName){
}
}
// ==================== PRIVATE ====================
// ==================== PRIVATE ====================
// ==================== private init ====================
// ==================== private init ====================
//init basic cell state
void World::initCells(){
@ -482,12 +490,12 @@ void World::initCells(){
Logger::getInstance().add("State cells", true);
for(int i=0; i<map.getSurfaceW(); ++i){
for(int j=0; j<map.getSurfaceH(); ++j){
SurfaceCell *sc= map.getSurfaceCell(i, j);
sc->setFowTexCoord(Vec2f(
i/(next2Power(map.getSurfaceW())-1.f),
j/(next2Power(map.getSurfaceH())-1.f)));
i/(next2Power(map.getSurfaceW())-1.f),
j/(next2Power(map.getSurfaceH())-1.f)));
for(int k=0; k<GameConstants::maxPlayers; k++){
sc->setExplored(k, false);
@ -519,7 +527,7 @@ void World::initSplattedTextures(){
}
}
//creates each faction looking at each faction name contained in GameSettings
//creates each faction looking at each faction name contained in GameSettings
void World::initFactionTypes(GameSettings *gs){
Logger::getInstance().add("Faction types", true);
@ -536,7 +544,7 @@ void World::initFactionTypes(GameSettings *gs){
for(int i=0; i<factions.size(); ++i){
const FactionType *ft= techTree.getType(gs->getFactionTypeName(i));
factions[i].init(
ft, gs->getFactionControl(i), &techTree, i, gs->getTeam(i),
ft, gs->getFactionControl(i), &techTree, i, gs->getTeam(i),
gs->getStartLocationIndex(i), i==thisFactionIndex, gs->getDefaultResources());
stats.setTeam(i, gs->getTeam(i));
@ -549,13 +557,13 @@ void World::initFactionTypes(GameSettings *gs){
void World::initMinimap(){
minimap.init(map.getW(), map.getH(), this);
Logger::getInstance().add("Compute minimap surface", true);
Logger::getInstance().add("Compute minimap surface", true);
}
//place units randomly aroud start location
void World::initUnits(){
Logger::getInstance().add("Generate elements", true);
Logger::getInstance().add("Generate elements", true);
//put starting units
for(int i=0; i<getFactionCount(); ++i){
@ -565,7 +573,14 @@ void World::initUnits(){
const UnitType *ut= ft->getStartingUnit(j);
int initNumber= ft->getStartingUnitAmount(j);
for(int l=0; l<initNumber; l++){
Unit *unit= new Unit(getNextUnitId(), Vec2i(0), ut, f, &map);
//!!!
if(Socket::enableDebugText) printf("In [%s::%s] A\n",__FILE__,__FUNCTION__);
float unitRotation = game->getGui()->getUnitTypeBuildRotation(ut->getId());
if(Socket::enableDebugText) printf("In [%s::%s] B\n",__FILE__,__FUNCTION__);
Unit *unit= new Unit(getNextUnitId(), Vec2i(0), ut, f, &map, unitRotation);
int startLocationIndex= f->getStartLocationIndex();
if(placeUnit(map.getStartLocation(startLocationIndex), generationArea, unit, true)){
@ -573,7 +588,7 @@ void World::initUnits(){
unit->born();
}
else{
throw runtime_error("Unit cant be placed, this error is caused because there is no enough place to put the units near its start location, make a better map: "+unit->getType()->getName() + " Faction: "+intToStr(i));
throw runtime_error("Unit cant be placed, this error is caused because there is no enough place to put the units near its start location, make a better map: "+unit->getType()->getName() + " Faction: "+intToStr(i));
}
if(unit->getType()->hasSkillClass(scBeBuilt)){
map.flatternTerrain(unit);
@ -601,10 +616,10 @@ void World::initExplorationState(){
}
// ==================== exploration ====================
// ==================== exploration ====================
void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex){
Vec2i newSurfPos= Map::toSurfCoords(newPos);
int surfSightRange= sightRange/Map::cellScale+1;
@ -614,26 +629,26 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex){
Vec2i currRelPos= Vec2i(i, j);
Vec2i currPos= newSurfPos + currRelPos;
if(map.isInsideSurface(currPos)){
SurfaceCell *sc= map.getSurfaceCell(currPos);
//explore
if(Vec2i(0).dist(currRelPos) < surfSightRange+indirectSightRange+1){
sc->setExplored(teamIndex, true);
}
//visible
if(Vec2i(0).dist(currRelPos) < surfSightRange){
sc->setVisible(teamIndex, true);
}
}
}
}
}
}
//computes the fog of war texture, contained in the minimap
void World::computeFow(){
//reset texture
minimap.resetFowTex();
@ -647,7 +662,7 @@ void World::computeFow(){
}
}
}
//compute cells
for(int i=0; i<getFactionCount(); ++i){
for(int j=0; j<getFaction(i)->getUnitCount(); ++j){
@ -681,14 +696,14 @@ void World::computeFow(){
const Unit *unit= faction->getUnit(j);
if(unit->isOperative()){
int sightRange= unit->getType()->getSight();
//iterate through all cells
PosCircularIterator pci(&map, unit->getPos(), sightRange+indirectSightRange);
while(pci.next()){
Vec2i pos= pci.getPos();
Vec2i surfPos= Map::toSurfCoords(pos);
//compute max alpha
float maxAlpha;
if(surfPos.x>1 && surfPos.y>1 && surfPos.x<map.getSurfaceW()-2 && surfPos.y<map.getSurfaceH()-2){
@ -705,7 +720,7 @@ void World::computeFow(){
float alpha;
float dist= unit->getPos().dist(pos);
if(dist>sightRange){
alpha= clamp(1.f-(dist-sightRange)/(indirectSightRange), 0.f, maxAlpha);
alpha= clamp(1.f-(dist-sightRange)/(indirectSightRange), 0.f, maxAlpha);
}
else{
alpha= maxAlpha;
@ -718,4 +733,4 @@ void World::computeFow(){
}
}
}}//end namespace
}}//end namespace

View File

@ -3,9 +3,9 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================
@ -86,13 +86,14 @@ private:
//config
bool fogOfWar;
int fogOfWarSmoothingFrameSkip;
bool fogOfWarSmoothing;
bool fogOfWarSmoothing;
Game *game;
public:
World();
void end(); //to die before selection does
//get
//get
int getMaxPlayers() const {return map.getMaxPlayers();}
int getThisFactionIndex() const {return thisFactionIndex;}
int getThisTeamIndex() const {return thisTeamIndex;}
@ -120,7 +121,7 @@ public:
void loadTech(const string &dir, set<string> &factions, Checksum* checksum);
void loadMap(const string &path, Checksum* checksum);
void loadScenario(const string &path, Checksum* checksum);
//misc
void update();
Unit* findUnitById(int id);
@ -145,7 +146,7 @@ public:
int getUnitCountOfType(int factionIndex, const string &typeName);
private:
void initCells();
void initSplattedTextures();
void initFactionTypes(GameSettings *gs);
@ -153,7 +154,7 @@ private:
void initUnits();
void initMap();
void initExplorationState();
//misc
void tick();
void computeFow();

0
source/glest_map_editor/main.cpp Normal file → Executable file
View File

View File

4
source/shared_lib/sources/graphics/gl/shader_gl.cpp Normal file → Executable file
View File

@ -3,8 +3,8 @@
//
// Copyright (C) 2001-2008 Martiño Figueroa
//
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// You can redistribute this code and/or modify it under
// the terms of the GNU General Public License as published
// by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version
// ==============================================================