Debian Codegraph @

engine/unit/unittype.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name unittype.cpp - The unit types. */
11 //
12 // (c) Copyright 1998-2008 by Lutz Sammer and Jimmy Salmon
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 //@{
30
31 /*----------------------------------------------------------------------------
32 -- Includes
33 ----------------------------------------------------------------------------*/
34
35 #include "stratagus.h"
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <string>
42 #include <map>
43
44 #include "video.h"
45 #include "map.h"
46 #include "sound.h"
47 #include "unitsound.h"
48 #include "construct.h"
49 #include "unittype.h"
50 #include "animation.h"
51 #include "player.h"
52 #include "missile.h"
53 #include "script.h"
54 #include "spells.h"
55 #include "iolib.h"
56 #include "luacallback.h"
57
58 /*----------------------------------------------------------------------------
59 -- Variables
60 ----------------------------------------------------------------------------*/
61
62 std::vector<CUnitType *> UnitTypes; /// unit-types definition
63 std::map<std::string, CUnitType *> UnitTypeMap;
64
65 /**
66 ** Default names for the resources.
67 */
68 std::string DefaultResourceNames[MaxCosts];
69
70 /**
71 ** Default names for the resources used for display (localized).
72 */
73 std::string DefaultDisplayResourceNames[MaxCosts];
74
75 /*----------------------------------------------------------------------------
76 -- Functions
77 ----------------------------------------------------------------------------*/
78
79 CUnitType::CUnitType() :
80 Slot(0), Width(0), Height(0), OffsetX(0), OffsetY(0), DrawLevel(0),
81 ShadowWidth(0), ShadowHeight(0), ShadowOffsetX(0), ShadowOffsetY(0),
82 Animations(NULL), StillFrame(0),
83 DeathExplosion(NULL), CorpseType(NULL),
84 Construction(NULL), RepairHP(0), TileWidth(0), TileHeight(0),
85 BoxWidth(0), BoxHeight(0), NumDirections(0), MinAttackRange(0),
86 ReactRangeComputer(0), ReactRangePerson(0), Priority(0),
87 BurnPercent(0), BurnDamageRate(0), RepairRange(0),
88 CanCastSpell(NULL), AutoCastActive(NULL),
89 CanTransport(false), MaxOnBoard(0),
90 UnitType(UnitTypeLand), DecayRate(0), AnnoyComputerFactor(0),
91 MouseAction(0), Points(0), CanTarget(0),
92 Flip(0), Revealer(0),
93 ExplodeWhenKilled(0), Building(0), VisibleUnderFog(0),
94 Coward(0), AttackFromTransporter(0),
95 Vanishes(0), GroundAttack(0), ShoreBuilding(0), CanAttack(0),
96 CanHarvestFrom(0), Harvester(0),
97 Neutral(0), SelectableByRectangle(0), IsNotSelectable(0), Decoration(0),
98 Indestructible(0), Organic(0), Variable(NULL),
99 ProductionEfficiency(100), FieldFlags(0), MovementMask(0),
100 ExplicitAllowTerrainMask(0), ExplicitForbidTerrainMask(0),
101 Sprite(NULL), ShadowSprite(NULL)
102 {
103 memset(&NeutralMinimapColorRGB, 0, sizeof(NeutralMinimapColorRGB));
104 memset(ProductionRate, 0, sizeof(ProductionRate));
105 memset(MaxUtilizationRate, 0, sizeof(MaxUtilizationRate));
106 memset(ProductionCosts, 0, sizeof(ProductionCosts));
107 memset(StorageCapacity, 0, sizeof(StorageCapacity));
108 }
109
110
111 CUnitType::~CUnitType()
112 {
113 delete DeathExplosion;
114
115 delete[] Variable;
116
117 for (int i = 0; i < PlayerMax; ++i) {
118 delete[] Stats[i].Variables;
119 }
120
121 // Free Building Restrictions if there are any
122 for (std::vector<CBuildRestriction *>::iterator b = BuildingRules.begin();
123 b != BuildingRules.end(); ++b) {
124 delete *b;
125 }
126 BuildingRules.clear();
127
128 delete[] CanCastSpell;
129 delete[] AutoCastActive;
130
131 CGraphic::Free(Sprite);
132 CGraphic::Free(ShadowSprite);
133 }
134
135 /**
136 ** Update the player stats for changed unit types.
137 ** @param reset indicates wether default value should be set to each stat (level, upgrades)
138 */
139 void UpdateStats(int reset)
140 {
141 CUnitType *type;
142 CUnitStats *stats;
143
144 //
145 // Update players stats
146 //
147 for (size_t j = 0; j < UnitTypes.size(); ++j) {
148 type = UnitTypes[j];
149 if (reset) {
150 // LUDO : FIXME : reset loading of player stats !
151 for (int player = 0; player < PlayerMax; ++player) {
152 stats = &type->Stats[player];
153 if (!stats->Variables) {
154 stats->Variables = new CVariable[UnitTypeVar.NumberVariable];
155 }
156 for (int i = 0; i < UnitTypeVar.NumberVariable; ++i) {
157 stats->Variables[i] = type->Variable[i];
158 }
159 }
160 }
161
162 //
163 // As side effect we calculate the movement flags/mask here.
164 //
165 switch (type->UnitType) {
166 case UnitTypeLand: // on land
167 type->MovementMask =
168 MapFieldLandUnit |
169 MapFieldSeaUnit |
170 MapFieldBuilding | // already occuppied
171 MapFieldCoastAllowed |
172 MapFieldShallowWater |
173 MapFieldDeepWater | // can't move on this
174 MapFieldUnpassable;
175 break;
176 case UnitTypeFly: // in air
177 type->MovementMask =
178 MapFieldAirUnit; // already occuppied
179 break;
180 case UnitTypeNaval: // on water
181 type->MovementMask =
182 MapFieldLandUnit |
183 MapFieldSeaUnit |
184 MapFieldBuilding | // already occupied
185 MapFieldLandAllowed; // can't move on this
186 // Johns: MapFieldUnpassable only for land units?
187 if (!type->CanTransport) {
188 type->MovementMask |=
189 MapFieldCoastAllowed |
190 MapFieldUnpassable;
191 }
192 break;
193 default:
194 DebugPrint("Where moves this unit?\n");
195 type->MovementMask = 0;
196 break;
197 }
198 if (type->Building || type->ShoreBuilding) {
199 // Shore building is something special.
200 if (type->ShoreBuilding) {
201 type->MovementMask =
202 MapFieldLandUnit |
203 MapFieldSeaUnit |
204 MapFieldBuilding | // already occuppied
205 MapFieldLandAllowed; // can't build on this
206 }
207 // Neutral harvestable units such as rocks and trees
208 // are marked as buildings because they cannot move
209 // and their corpses should not fuel spells. They
210 // should however ignore MapFieldNoBuilding so that
211 // the map author can place them wherever desired.
212 if (!type->Neutral) {
213 type->MovementMask |= MapFieldNoBuilding;
214 }
215 //
216 // A little chaos, buildings without HP can be entered.
217 // The oil-patch is a very special case.
218 //
219 if (type->Variable[HP_INDEX].Max) {
220 type->FieldFlags = MapFieldBuilding;
221 } else {
222 type->FieldFlags = MapFieldNoBuilding;
223 }
224 } else switch (type->UnitType) {
225 case UnitTypeLand: // on land
226 type->FieldFlags = MapFieldLandUnit;
227 break;
228 case UnitTypeFly: // in air
229 type->FieldFlags = MapFieldAirUnit;
230 break;
231 case UnitTypeNaval: // on water
232 type->FieldFlags = MapFieldSeaUnit;
233 break;
234 default:
235 DebugPrint("Where moves this unit?\n");
236 type->FieldFlags = 0;
237 break;
238 }
239
240 type->MovementMask &= ~type->ExplicitAllowTerrainMask;
241 type->MovementMask |= type->ExplicitForbidTerrainMask;
242 }
243 }
244
245 /**
246 ** Get the animations structure by ident.
247 **
248 ** @param ident Identifier for the animation.
249 **
250 ** @return Pointer to the animation structure.
251 */
252 CAnimations *AnimationsByIdent(const std::string &ident)
253 {
254 std::map<std::string, CAnimations *>::const_iterator found
255 = AnimationMap.find(ident);
256 if (found != AnimationMap.end()) {
257 return found->second;
258 } else {
259 return NULL;
260 }
261 }
262
263 /**
264 ** Find unit-type by identifier.
265 **
266 ** @param ident The unit-type identifier.
267 **
268 ** @return Unit-type pointer.
269 */
270 CUnitType *UnitTypeByIdent(const std::string &ident)
271 {
272 std::map<std::string, CUnitType *>::const_iterator found
273 = UnitTypeMap.find(ident);
274 if (found != UnitTypeMap.end()) {
275 return found->second;
276 } else {
277 return NULL;
278 }
279 }
280
281 /**
282 ** Allocate an empty unit-type slot.
283 **
284 ** @param ident Identifier to identify the slot (malloced by caller!).
285 **
286 ** @return New allocated (zeroed) unit-type pointer.
287 */
288 CUnitType *NewUnitTypeSlot(const std::string &ident)
289 {
290 CUnitType *type;
291
292 type = new CUnitType;
293 if (!type) {
294 fprintf(stderr, "Out of memory\n");
295 ExitFatal(-1);
296 }
297 type->Slot = UnitTypes.size();
298 type->Ident = ident;
299 type->Variable = new CVariable[UnitTypeVar.NumberVariable];
300 memcpy(type->Variable, UnitTypeVar.Variable,
301 UnitTypeVar.NumberVariable * sizeof(*type->Variable));
302
303 UnitTypes.push_back(type);
304 UnitTypeMap[type->Ident] = type;
305 return type;
306 }
307
308 /**
309 ** Draw unit-type on map.
310 **
311 ** @param type Unit-type pointer.
312 ** @param sprite Sprite to use for drawing
313 ** @param player Player number for color substitution.
314 ** @param frame Animation frame of unit-type.
315 ** @param x Screen X pixel postion to draw unit-type.
316 ** @param y Screen Y pixel postion to draw unit-type.
317 **
318 ** @todo Do screen position caculation in high level.
319 ** Better way to handle in x mirrored sprites.
320 */
321 void DrawUnitType(const CUnitType *type, CPlayerColorGraphic *sprite, int player, int frame,
322 int x, int y)
323 {
324 // FIXME: move this calculation to high level.
325 x -= (type->Width - type->TileWidth * TileSizeX) / 2;
326 y -= (type->Height - type->TileHeight * TileSizeY) / 2;
327 x += type->OffsetX;
328 y += type->OffsetY;
329
330 if (type->Flip) {
331 if (frame < 0) {
332 sprite->DrawPlayerColorFrameClipX(player, -frame - 1, x, y);
333 } else {
334 sprite->DrawPlayerColorFrameClip(player, frame, x, y);
335 }
336 } else {
337 int row;
338
339 row = type->NumDirections / 2 + 1;
340 if (frame < 0) {
341 frame = ((-frame - 1) / row) * type->NumDirections + type->NumDirections - (-frame - 1) % row;
342 } else {
343 frame = (frame / row) * type->NumDirections + frame % row;
344 }
345 sprite->DrawPlayerColorFrameClip(player, frame, x, y);
346 }
347 }
348
349 /**
350 ** Get the still animation frame
351 */
352 static int GetStillFrame(CUnitType *type)
353 {
354 CAnimation *anim;
355
356 anim = type->Animations->Still;
357 while (anim) {
358 if (anim->Type == AnimationFrame) {
359 // Use the frame facing down
360 return anim->D.Frame.Frame + type->NumDirections / 2;
361 } else if (anim->Type == AnimationExactFrame) {
362 return anim->D.Frame.Frame;
363 }
364 anim = anim->Next;
365 }
366 return type->NumDirections / 2;
367 }
368
369 /**
370 ** Init unit types.
371 */
372 void InitUnitTypes(int reset_player_stats)
373 {
374 CUnitType *type;
375
376 for (size_t i = 0; i < UnitTypes.size(); ++i) {
377 type = UnitTypes[i];
378 Assert(type->Slot == (int)i);
379
380 // Add idents to hash.
381 UnitTypeMap[type->Ident] = UnitTypes[i];
382
383 // Determine still frame
384 type->StillFrame = GetStillFrame(type);
385
386 // Lookup BuildingTypes
387 for (std::vector<CBuildRestriction *>::iterator b = type->BuildingRules.begin();
388 b < type->BuildingRules.end(); ++b) {
389 (*b)->Init();
390 }
391 }
392
393 // LUDO : called after game is loaded -> don't reset stats !
394 UpdateStats(reset_player_stats); // Calculate the stats
395 }
396
397 /**
398 ** Loads the Sprite for a unit type
399 **
400 ** @param type type of unit to load
401 */
402 void LoadUnitTypeSprite(CUnitType *type)
403 {
404 if (!type->ShadowFile.empty()) {
405 type->ShadowSprite = CGraphic::ForceNew(type->ShadowFile, type->ShadowWidth,
406 type->ShadowHeight);
407 type->ShadowSprite->Load();
408 if (type->Flip) {
409 type->ShadowSprite->Flip();
410 }
411 type->ShadowSprite->MakeShadow();
412 }
413
414 if (!type->File.empty()) {
415 type->Sprite = CPlayerColorGraphic::New(type->File, type->Width, type->Height);
416 type->Sprite->Load();
417 if (type->Flip) {
418 type->Sprite->Flip();
419 }
420 }
421 }
422
423 /**
424 ** Load the graphics for the unit-types.
425 */
426 void LoadUnitTypes(void)
427 {
428 CUnitType *type;
429
430 for (size_t i = 0; i < UnitTypes.size(); ++i) {
431 type = UnitTypes[i];
432
433 //
434 // Lookup icons.
435 //
436 type->Icon.Load();
437 //
438 // Lookup missiles.
439 //
440 type->Missile.Missile = MissileTypeByIdent(type->Missile.Name);
441 if (!type->Explosion.Name.empty()) {
442 type->Explosion.Missile = MissileTypeByIdent(type->Explosion.Name);
443 }
444 //
445 // Lookup corpse.
446 //
447 if (!type->CorpseName.empty()) {
448 type->CorpseType = UnitTypeByIdent(type->CorpseName);
449 }
450
451 //
452 // Load Sprite
453 //
454 if (!type->Sprite) {
455 ShowLoadProgress("Unit \"%s\"", type->Name.c_str());
456 LoadUnitTypeSprite(type);
457 }
458 }
459 }
460
461 /**
462 ** Clean animation
463 */
464 static void CleanAnimation(CAnimation *anim)
465 {
466 int i;
467 CAnimation *ptr;
468
469 ptr = anim;
470 while (ptr->Type != AnimationNone) {
471 if (ptr->Type == AnimationSound) {
472 delete[] ptr->D.Sound.Name;
473 } else if (ptr->Type == AnimationRandomSound) {
474 for (i = 0; i < ptr->D.RandomSound.NumSounds; ++i) {
475 delete[] ptr->D.RandomSound.Name[i];
476 }
477 delete[] ptr->D.RandomSound.Name;
478 delete[] ptr->D.RandomSound.Sound;
479 }
480 ++ptr;
481 }
482 delete[] anim;
483 }
484
485 /**
486 ** Cleanup the unit-type module.
487 */
488 void CleanUnitTypes(void)
489 {
490 // Clean all animations.
491 for (int j = 0; j < NumAnimations; ++j) {
492 CleanAnimation(AnimationsArray[j]);
493 }
494 NumAnimations = 0;
495
496 std::map<std::string, CAnimations *>::iterator at;
497 for (at = AnimationMap.begin(); at != AnimationMap.end(); ++at) {
498 delete (*at).second;
499 }
500 AnimationMap.clear();
501
502 // Clean all unit-types
503
504 for (size_t i = 0; i < UnitTypes.size(); ++i) {
505 delete UnitTypes[i];
506 }
507 UnitTypes.clear();
508 UnitTypeMap.clear();
509
510 for (int j = 0; j < UnitTypeVar.NumberVariable; ++j) { // User defined variables
511 delete[] UnitTypeVar.VariableName[j];
512 }
513 delete[] UnitTypeVar.VariableName;
514 UnitTypeVar.VariableName = NULL;
515 delete[] UnitTypeVar.Variable;
516 UnitTypeVar.Variable = NULL;
517 UnitTypeVar.NumberVariable = 0;
518 for (std::vector<CDecoVar *>::iterator it = UnitTypeVar.DecoVar.begin();
519 it != UnitTypeVar.DecoVar.end(); ++it) {
520 delete (*it);
521 }
522 UnitTypeVar.DecoVar.clear();
523 }
524
525 //@}