Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/playability/src/world_entities/weapons/weapon.cc @ 10111

Last change on this file since 10111 was 10037, checked in by nicolasc, 18 years ago

added some comments
made swarm missile spin

File size: 20.3 KB
Line 
1
2/*
3   orxonox - the future of 3D-vertical-scrollers
4
5   Copyright (C) 2004 orx
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 2, or (at your option)
10   any later version.
11
12### File Specific
13   main-programmer: Patrick Boenzli
14   co-programmer: Benjamin Grauer
15
16   2005-07-15: Benjamin Grauer: restructurating the entire Class
17*/
18
19#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_WEAPON
20
21#include "weapon.h"
22
23#include "loading/fast_factory.h"
24#include "world_entities/projectiles/projectile.h"
25
26#include "util/loading/factory.h"
27#include "util/loading/load_param.h"
28#include "state.h"
29#include "animation3d.h"
30
31#include "sound_source.h"
32#include "sound_buffer.h"
33#include "resource_sound_buffer.h"
34
35#include "elements/glgui_energywidget.h"
36
37ObjectListDefinition(Weapon);
38
39////////////////////
40// INITAILISATION //
41// SETTING VALUES //
42////////////////////
43/**
44 * standard constructor
45 *
46 * creates a new weapon
47*/
48Weapon::Weapon ()
49{
50  this->init();
51}
52
53/**
54 * standard deconstructor
55*/
56Weapon::~Weapon ()
57{
58  for (int i = 0; i < WS_STATE_COUNT; i++)
59    if (this->animation[i] && Animation::objectList().exists(animation[i]))  //!< @todo this should check animation3D
60      delete this->animation[i];
61
62  if (OrxSound::SoundSource::objectList().exists(this->soundSource))
63    delete this->soundSource;
64}
65
66/**
67 * @brief creates a new Weapon of type weaponID and returns it.
68 * @param weaponID the WeaponID type to create.
69 * @returns the newly created Weapon.
70 */
71Weapon* Weapon::createWeapon(const ClassID& weaponID)
72{
73  BaseObject* createdObject = Factory::fabricate(weaponID);
74  if (createdObject != NULL)
75  {
76    if (createdObject->isA(Weapon::staticClassID()))
77      return dynamic_cast<Weapon*>(createdObject);
78    else
79    {
80      delete createdObject;
81      return NULL;
82    }
83  }
84  return NULL;
85}
86
87Weapon* Weapon::createWeapon(const std::string& weaponName)
88{
89  BaseObject* createdObject = Factory::fabricate(weaponName);
90  if (createdObject != NULL)
91  {
92    if (createdObject->isA(Weapon::staticClassID()))
93      return dynamic_cast<Weapon*>(createdObject);
94    else
95    {
96      delete createdObject;
97      return NULL;
98    }
99  }
100  return NULL;
101}
102
103
104/**
105 * initializes the Weapon with ALL default values
106 *
107 * This Sets the default values of the Weapon
108 */
109void Weapon::init()
110{
111  this->registerObject(this, Weapon::_objectList);
112  this->currentState     = WS_INACTIVE;            //< Normaly the Weapon is Inactive
113  this->requestedAction  = WA_NONE;                //< No action is requested by default
114  this->stateDuration    = 0.0;                    //< All the States have zero duration
115  for (int i = 0; i < WS_STATE_COUNT; i++)         //< Every State has:
116  {
117    this->times[i] = 0.0;                        //< An infinitesimal duration
118    this->animation[i] = NULL;                   //< No animation
119  }
120
121  this->soundSource = new OrxSound::SoundSource(this);       //< Every Weapon has exacty one SoundSource.
122  this->emissionPoint.setParent(this);             //< One EmissionPoint, that is a PNode connected to the weapon. You can set this to the exitting point of the Projectiles
123  this->emissionPoint.setName("EmissionPoint");
124  this->emissionPoint.addNodeFlags(PNODE_PROHIBIT_DELETE_WITH_PARENT);
125
126  this->defaultTarget = NULL;                      //< Nothing is Targeted by default.
127
128  this->projectile = NullClass::staticClassID();         //< No Projectile Class is Connected to this weapon
129  this->projectileFactory = NULL;                  //< No Factory generating Projectiles is selected.
130
131  this->hideInactive = true;                       //< The Weapon will be hidden if it is inactive (by default)
132
133  this->minCharge = 1.0;                           //< The minimum charge the Weapon can hold is 1 unit.
134  this->maxCharge = 1.0;                           //< The maximum charge is also one unit.
135
136  this->energy = 10;                               //< The secondary Buffer (before we have to reload)
137  this->energyMax = 10.0;                          //< How much energy can be carried
138  this->capability = WTYPE_ALL;                    //< The Weapon has all capabilities @see W_Capability.
139
140  this->energyWidget = NULL;
141
142  // set this object to be synchronized over network
143  //this->setSynchronized(true);
144}
145
146/**
147 * loads the Parameters of a Weapon
148 * @param root the XML-Element to load the Weapons settings from
149 */
150void Weapon::loadParams(const TiXmlElement* root)
151{
152  WorldEntity::loadParams(root);
153
154  LoadParam(root, "projectile", this, Weapon, setProjectileTypeC)
155  .describe("Sets the name of the Projectile to load onto the Entity");
156
157  LoadParam(root, "emission-point", this, Weapon, setEmissionPoint)
158  .describe("Sets the Point of emission of this weapon");
159
160  LoadParam(root, "state-duration", this, Weapon, setStateDuration)
161  .describe("Sets the duration of a given state (1: state-Name; 2: duration in seconds)");
162
163  LoadParam(root, "action-sound", this, Weapon, setActionSound)
164  .describe("Sets a given sound to an action (1: action-Name; 2: name of the sound (relative to the Data-Path))");
165}
166
167
168/**
169 * sets the Projectile to use for this weapon.
170 * @param projectile The ID of the Projectile to use
171 * @returns true, if it was sucessfull, false on error
172 *
173 * be aware, that this function does not create Factories, as this is job of Projecitle/Bullet-classes.
174 * What it does, is telling the Weapon what Projectiles it can Emit.
175 */
176void Weapon::setProjectileType(const ClassID& projectile)
177{
178  this->projectile = projectile;
179  this->projectileFactory = FastFactory::searchFastFactory(projectile);
180  if (this->projectileFactory == NULL)
181  {
182    PRINTF(1)("unable to find FastFactory for the Projectile.\n");
183    return;
184  }
185  else
186  {
187    // grabbing Parameters from the Projectile to have them at hand here.
188    Projectile* pj = dynamic_cast<Projectile*>(this->projectileFactory->resurrect());
189    this->minCharge = pj->getMinEnergy();
190    this->maxCharge = pj->getHealthMax();
191    this->chargeable = pj->isChageable();
192    this->projectileFactory->kill(pj);
193  }
194}
195
196
197/**
198 * @see bool Weapon::setProjectile(ClassID projectile)
199 * @param projectile the Name of the Projectile.
200 */
201void Weapon::setProjectileTypeC(const std::string& projectile)
202{
203  FastFactory* tmpFac = FastFactory::searchFastFactory(projectile);
204  if (tmpFac != NULL)
205  {
206    this->setProjectileType(tmpFac->getStoredID());
207  }
208  else
209  {
210    PRINTF(1)("Projectile %s does not exist for weapon %s\n", projectile.c_str(), this->getCName());
211  }
212}
213
214
215/**
216 * prepares Projectiles of the Weapon
217 * @param count how many Projectiles to create (they will be stored in the ProjectileFactory)
218 */
219void Weapon::prepareProjectiles(unsigned int count)
220{
221  if (likely(this->projectileFactory != NULL))
222    projectileFactory->prepare(count);
223  else
224    PRINTF(2)("unable to create %d projectile for Weapon %s::%s\n", count, this->getClassCName(), this->getCName());
225}
226
227
228/**
229 * resurects and returns a Projectile
230 * @returns a Projectile on success, NULL on error
231 *
232 * errors: 1. (ProjectileFastFactory not Found)
233 *         2. No more Projectiles availiable.
234 */
235Projectile* Weapon::getProjectile()
236{
237  if (likely (this->projectileFactory != NULL))
238  {
239    Projectile* pj = dynamic_cast<Projectile*>(this->projectileFactory->resurrect());
240    pj->toList((OM_LIST)(this->getOMListNumber()+1));
241    return pj;
242  }
243  else
244  {
245    PRINTF(2)("No projectile defined for Weapon %s(%s) can't return any\n", this->getCName(), this->getClassCName());
246    return NULL;
247  }
248}
249
250
251/**
252 * sets the emissionPoint's relative position from the Weapon
253 * @param point the Point relative to the mass-point of the Weapon
254 */
255void Weapon::setEmissionPoint(const Vector& point)
256{
257  this->emissionPoint.setRelCoor(point);
258}
259
260
261/**
262 * assigns a Sound-file to an action
263 * @param action the action the sound should be assigned too
264 * @param soundFile the soundFile's relative position to the data-directory (will be looked for by the ResourceManager)
265 */
266void Weapon::setActionSound(WeaponAction action, const std::string& soundFile)
267{
268  if (action >= WA_ACTION_COUNT)
269    return;
270
271  else if (!soundFile.empty())
272  {
273    this->soundBuffers[action] = OrxSound::ResourceSoundBuffer(soundFile);
274    if (this->soundBuffers[action].loaded())
275    {
276      PRINTF(4)("Loaded sound %s to action %s.\n", soundFile.c_str(), actionToChar(action));
277    }
278    else
279    {
280      PRINTF(2)("Failed to load sound %s to %s.\n.", soundFile.c_str(), actionToChar(action));
281    }
282  }
283  else
284    this->soundBuffers[action] = OrxSound::SoundBuffer();
285}
286
287
288/**
289 * creates/returns an Animation3D for a certain State.
290 * @param state what State should the Animation be created/returned for
291 * @param node the node this Animation should apply to. (NULL is fine if the animation was already created)
292 * @returns The created animation.Animation(), NULL on error (or if the animation does not yet exist).
293 *
294 * This function does only generate the Animation Object, and if set it will
295 * automatically be executed, when a certain State is reached.
296 * What this does not do, is set keyframes, you have to operate on the returned animation.
297 */
298Animation3D* Weapon::getAnimation(WeaponState state, PNode* node)
299{
300  if (state >= WS_STATE_COUNT) // if the state is not known
301    return NULL;
302
303  if (unlikely(this->animation[state] == NULL)) // if the animation does not exist yet create it.
304  {
305    if (likely(node != NULL))
306      return this->animation[state] = new Animation3D(node);
307    else
308    {
309      PRINTF(2)("Node not defined for the Creation of the 3D-animation of state %s\n", stateToChar(state));
310      return NULL;
311    }
312  }
313  else
314    return this->animation[state];
315}
316
317OrxGui::GLGuiWidget* Weapon::getEnergyWidget()
318{
319  if (this->energyWidget == NULL)
320  {
321    this->energyWidget = new OrxGui::GLGuiEnergyWidget();
322    this->energyWidget->setDisplayedName(this->getClassCName());
323    this->energyWidget->setSize2D( 20, 100);
324    this->energyWidget->setMaximum(this->getEnergyMax());
325    this->energyWidget->setValue(this->getEnergy());
326  }
327  return this->energyWidget;
328}
329
330void Weapon::updateWidgets()
331{
332  if (this->energyWidget != NULL)
333  {
334    this->energyWidget->setMaximum(this->energyMax);
335    this->energyWidget->setValue(this->energy);
336  }
337}
338
339/////////////////
340//  EXECUTION  //
341// GAME ACTION //
342/////////////////
343/**
344 * request an action that should be executed,
345 * @param action the next action to take
346 *
347 * This function must be called instead of the actions (like fire/reload...)
348 * to make all the checks needed to have a usefull WeaponSystem.
349 */
350void Weapon::requestAction(WeaponAction action)
351{
352  if (likely(this->isActive()))
353  {
354    /** Disabled for releaseFire() from WM*/
355    //if (this->requestedAction != WA_NONE)
356    //  return;
357    PRINTF(5)("next action will be %s in %f seconds\n", actionToChar(action), this->stateDuration);
358    this->requestedAction = action;
359  }
360  //else
361  else if (unlikely(action == WA_ACTIVATE))
362  {
363    this->currentState = WS_ACTIVATING;
364    this->requestedAction = WA_ACTIVATE;
365  }
366}
367
368
369/**
370 * adds energy to the Weapon
371 * @param energyToAdd The amount of energy
372 * @returns the amount of energy we did not pick up, because the weapon is already full
373 */
374float Weapon::increaseEnergy(float energyToAdd)
375{
376  float maxAddEnergy = this->energyMax - this->energy;
377
378  if (maxAddEnergy >= energyToAdd)
379  {
380    this->energy += energyToAdd;
381    this->updateWidgets();
382    return 0.0;
383  }
384  else
385  {
386    this->energy += maxAddEnergy;
387    this->updateWidgets();
388    return energyToAdd - maxAddEnergy;
389  }
390 
391}
392
393
394////////////////////////////////////////////////////////////
395// WEAPON INTERNALS                                       //
396// These are functions, that no other Weapon should over- //
397// write. No class has direct Access to them, as it is    //
398// quite a complicated process, handling a Weapon from    //
399// the outside                                            //
400////////////////////////////////////////////////////////////
401/**
402 * executes an action, and with it starts a new State.
403 * @return true, if it worked, false otherwise
404 *
405 * This function checks, wheter the possibility of executing an action is valid,
406 * and does all the necessary stuff, to execute them. If an action does not succeed,
407 * it tries to go around it. (ex. shoot->noAmo->reload()->wait until shoot comes again)
408 */
409bool Weapon::execute()
410{
411#if DEBUG_LEVEL > 4
412  PRINTF(4)("trying to execute action %s\n", actionToChar(this->requestedAction));
413  this->debug();
414#endif
415
416  WeaponAction action = this->requestedAction;
417  this->requestedAction = WA_NONE;
418
419  switch (action)
420  {
421    case WA_SHOOT:
422    return this->fireW();
423    break;
424    case WA_CHARGE:
425    return this->chargeW();
426    break;
427    case WA_RELOAD:
428    return this->reloadW();
429    break;
430    case WA_DEACTIVATE:
431    return this->deactivateW();
432    break;
433    case WA_ACTIVATE:
434    return this->activateW();
435    break;
436    default:
437    PRINTF(2)("Action %s Not Implemented yet \n", Weapon::actionToChar(action));
438    return false;
439  }
440}
441
442/**
443 * checks and activates the Weapon.
444 * @return true on success.
445 */
446bool Weapon::activateW()
447{
448  //  if (this->currentState == WS_INACTIVE)
449  {
450    // play Sound
451    if (likely(this->soundBuffers[WA_ACTIVATE].loaded()))
452      this->soundSource->play(this->soundBuffers[WA_ACTIVATE]);
453    this->updateWidgets();
454    // activate
455    PRINTF(4)("Activating the Weapon %s\n", this->getCName());
456    this->activate();
457    // setting up for next action
458    this->enterState(WS_ACTIVATING);
459  }
460  return true;
461}
462
463/**
464 * checks and deactivates the Weapon
465 * @return true on success.
466 */
467bool Weapon::deactivateW()
468{
469  //  if (this->currentState != WS_INACTIVE)
470  {
471    PRINTF(4)("Deactivating the Weapon %s\n", this->getCName());
472    // play Sound
473    if (this->soundBuffers[WA_DEACTIVATE].loaded())
474      this->soundSource->play(this->soundBuffers[WA_DEACTIVATE]);
475    // deactivate
476    this->deactivate();
477    this->enterState(WS_DEACTIVATING);
478  }
479
480  return true;
481}
482
483/**
484 * checks and charges the Weapon
485 * @return true on success.
486 */
487bool Weapon::chargeW()
488{
489  if ( this->currentState != WS_INACTIVE && this->energy >= this->minCharge)
490  {
491    // playing Sound
492    if (this->soundBuffers[WA_CHARGE].loaded())
493      this->soundSource->play(this->soundBuffers[WA_CHARGE]);
494
495    // charge
496    this->charge();
497    // setting up for the next state
498    this->enterState(WS_CHARGING);
499  }
500  else // deactivate the Weapon if we do not have enough energy
501  {
502    this->requestAction(WA_RELOAD);
503  }
504  return true;
505}
506
507/**
508 * checks and fires the Weapon
509 * @return true on success.
510 */
511bool Weapon::fireW()
512{
513  //if (likely(this->currentState != WS_INACTIVE))
514  if (this->minCharge <= this->energy)
515  {
516    // playing Sound
517    if (this->soundBuffers[WA_SHOOT].loaded())
518      this->soundSource->play(this->soundBuffers[WA_SHOOT]);
519    // fire
520    this->energy -= this->minCharge;
521    this->fire();
522    // setting up for the next state
523    this->enterState(WS_SHOOTING);
524    this->updateWidgets();
525  }
526  else  // reload if we still have the charge
527  {
528    this->requestAction(WA_RELOAD);
529    this->execute();
530  }
531  return true;
532}
533
534/**
535 * checks and Reloads the Weapon
536 * @return true on success.
537 */
538bool Weapon::reloadW()
539{
540  PRINTF(4)("Reloading Weapon %s\n", this->getCName());
541  if (!this->ammoContainer.isNull() &&
542      unlikely(this->energy + this->ammoContainer->getStoredEnergy() < this->minCharge))
543  {
544    //this->requestAction(WA_DEACTIVATE);
545    this->execute();
546    return false;
547  }
548
549
550  if (this->soundBuffers[WA_RELOAD].loaded())
551    this->soundSource->play(this->soundBuffers[WA_RELOAD]);
552
553  if (!this->ammoContainer.isNull())
554    this->ammoContainer->fillWeapon(this);
555  else
556  {
557    this->energy = this->energyMax;
558  }
559  this->updateWidgets();
560  this->reload();
561  this->enterState(WS_RELOADING);
562
563  return true;
564}
565
566/**
567 * enters the requested State, plays back animations updates the timing.
568 * @param state the state to enter.
569 */
570inline void Weapon::enterState(WeaponState state)
571{
572  PRINTF(4)("ENTERING STATE %s\n", stateToChar(state));
573  // playing animation if availiable
574  if (likely(this->animation[state] != NULL))
575    this->animation[state]->replay();
576
577  this->stateDuration += this->times[state];
578  this->currentState = state;
579}
580
581///////////////////
582//  WORLD-ENTITY //
583// FUNCTIONALITY //
584///////////////////
585/**
586 * tick signal for time dependent/driven stuff
587*/
588bool Weapon::tickW(float dt)
589{
590  //printf("%s ", stateToChar(this->currentState));
591
592  // setting up the timing properties
593  this->stateDuration -= dt;
594
595  if (this->stateDuration <= 0.0)
596  {
597    if (unlikely (this->currentState == WS_DEACTIVATING))
598    {
599      this->currentState = WS_INACTIVE;
600      return false;
601    }
602    else
603      this->currentState = WS_IDLE;
604
605    if (this->requestedAction != WA_NONE)
606    {
607      this->stateDuration = -dt;
608      this->execute();
609    }
610  }
611  return true;
612}
613
614
615
616
617//////////////////////
618// HELPER FUNCTIONS //
619//////////////////////
620/**
621 * checks wether all the Weapons functions are valid, and if it is possible to go to action with it.
622 * @todo IMPLEMENT the Weapons Check
623 */
624bool Weapon::check() const
625{
626  bool retVal = true;
627
628  //  if (this->projectile == NULL)
629  {
630    PRINTF(1)("There was no projectile assigned to the Weapon.\n");
631    retVal = false;
632  }
633
634
635
636
637  return retVal;
638}
639
640/**
641 * some nice debugging information about this Weapon
642 */
643void Weapon::debug() const
644{
645  PRINT(0)("Weapon-Debug %s, state: %s (duration: %fs), nextAction: %s\n", this->getCName(), Weapon::stateToChar(this->currentState), this->stateDuration, Weapon::actionToChar(requestedAction));
646  PRINT(0)("Energy: max: %f; current: %f; chargeMin: %f, chargeMax %f\n",
647           this->energyMax, this->energy, this->minCharge, this->maxCharge);
648
649
650}
651
652////////////////////////////////////////////////////////
653// static Definitions (transormators for readability) //
654////////////////////////////////////////////////////////
655/**
656 * Converts a String into an Action.
657 * @param action the String input holding the Action.
658 * @return The Action if known, WA_NONE otherwise.
659 */
660WeaponAction Weapon::charToAction(const std::string& action)
661{
662  if (action == "none")
663    return WA_NONE;
664  else if (action == "shoot")
665    return WA_SHOOT;
666  else if (action == "charge")
667    return WA_CHARGE;
668  else if (action == "reload")
669    return WA_RELOAD;
670  else if (action == "acitvate")
671    return WA_ACTIVATE;
672  else if (action == "deactivate")
673    return WA_DEACTIVATE;
674  else if (action == "special1")
675    return WA_SPECIAL1;
676  else
677  {
678    PRINTF(2)("action %s could not be identified.\n", action.c_str());
679    return WA_NONE;
680  }
681}
682
683/**
684 * converts an action into a String
685 * @param action the action to convert
686 * @return a String matching the name of the action
687 */
688const char* Weapon::actionToChar(WeaponAction action)
689{
690  switch (action)
691  {
692    case WA_SHOOT:
693    return "shoot";
694    break;
695    case WA_CHARGE:
696    return "charge";
697    break;
698    case WA_RELOAD:
699    return "reload";
700    break;
701    case WA_ACTIVATE:
702    return "activate";
703    break;
704    case WA_DEACTIVATE:
705    return "deactivate";
706    break;
707    case WA_SPECIAL1:
708    return "special1";
709    break;
710    default:
711    return "none";
712    break;
713  }
714}
715
716/**
717 * Converts a String into a State.
718 * @param state the String input holding the State.
719 * @return The State if known, WS_NONE otherwise.
720 */
721WeaponState Weapon::charToState(const std::string& state)
722{
723  if (state == "none")
724    return WS_NONE;
725  else if (state == "shooting")
726    return WS_SHOOTING;
727  else if (state == "charging")
728    return WS_CHARGING;
729  else if (state == "reloading")
730    return WS_RELOADING;
731  else if (state == "activating")
732    return WS_ACTIVATING;
733  else if (state == "deactivating")
734    return WS_DEACTIVATING;
735  else if (state == "inactive")
736    return WS_INACTIVE;
737  else if (state == "idle")
738    return WS_IDLE;
739  else
740  {
741    PRINTF(2)("state %s could not be identified.\n", state.c_str());
742    return WS_NONE;
743  }
744}
745
746/**
747 * converts a State into a String
748 * @param state the state to convert
749 * @return a String matching the name of the state
750 */
751const char* Weapon::stateToChar(WeaponState state)
752{
753  switch (state)
754  {
755    case WS_SHOOTING:
756    return "shooting";
757    break;
758    case WS_CHARGING:
759    return "charging";
760    break;
761    case WS_RELOADING:
762    return "reloading";
763    break;
764    case WS_ACTIVATING:
765    return "activating";
766    break;
767    case WS_DEACTIVATING:
768    return "deactivating";
769    break;
770    case WS_IDLE:
771    return "idle";
772    break;
773    case WS_INACTIVE:
774    return "inactive";
775    break;
776    default:
777    return "none";
778    break;
779  }
780}
Note: See TracBrowser for help on using the repository browser.