Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/formation/src/orxonox/controllers/Masterable.cc @ 8978

Last change on this file since 8978 was 8967, checked in by willis, 12 years ago

added DEFEND behaviour, fixed some orientation issue

File size: 33.4 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      Dominik Solenicki
26 *
27 */
28
29#include <climits>
30#include "controllers/Masterable.h"
31
32#include "core/CoreIncludes.h"
33
34#include "core/XMLPort.h"
35#include "core/command/ConsoleCommand.h"
36
37#include "worldentities/ControllableEntity.h"
38#include "worldentities/pawns/Pawn.h"
39#include "worldentities/pawns/TeamBaseMatchBase.h"
40#include "gametypes/TeamDeathmatch.h"
41#include "gametypes/Dynamicmatch.h"
42#include "gametypes/Gametype.h"
43#include "controllers/WaypointPatrolController.h"
44#include "controllers/NewHumanController.h"
45#include "controllers/DroneController.h"
46
47
48namespace orxonox
49{
50
51  SetConsoleCommand("Masterable", "formationflight",  &Masterable::formationflight);
52  SetConsoleCommand("Masterable", "masteraction",     &Masterable::masteraction);
53  SetConsoleCommand("Masterable", "followme",         &Masterable::followme);
54  SetConsoleCommand("Masterable", "passivebehaviour", &Masterable::passivebehaviour);
55  SetConsoleCommand("Masterable", "formationsize",    &Masterable::formationsize);
56
57
58
59
60  static const unsigned int STANDARD_MAX_FORMATION_SIZE = 9;
61  static const int RADIUS_TO_SEARCH_FOR_MASTERS = 5000;
62  static const int FORMATION_LENGTH =  110;
63  static const int FORMATION_WIDTH =  110;
64  static const int FREEDOM_COUNT = 4; //seconds the slaves in a formation will be set free when master attacks an enemy
65  static const float SPEED_MASTER = 0.6f;
66  static const float ROTATEFACTOR_MASTER = 0.2f;
67  static const float SPEED_FREE = 0.8f;
68  static const float ROTATEFACTOR_FREE = 0.8f;
69
70  Masterable::Masterable(BaseObject* creator) : Controller(creator)
71  {
72        RegisterObject(Masterable);
73
74        this->target_ = 0;
75        this->formationFlight_ = false;
76        this->passive_ = false;
77        this->maxFormationSize_ = STANDARD_MAX_FORMATION_SIZE;
78        this->myMaster_ = 0;
79        this->freedomCount_ = 0;
80
81        this->state_ = FREE;
82        this->mode_ = NORMAL;
83        this->specificMasterAction_ = NONE;
84        this->specificMasterActionHoldCount_  = 0;
85        this->bShooting_ = false;
86        this->bHasTargetPosition_ = false;
87        this->bHasTargetOrientation_=false;
88        this->speedCounter_ = 0.2f;
89        this->targetPosition_ = Vector3::ZERO;
90        //this->team_=-1;
91        this->target_.setCallback(createFunctor(&Masterable::targetDied, this));
92  }
93
94  Masterable::~Masterable()
95  {
96    if (this->isInitialized())
97        {
98            this->removeFromFormation();
99
100            for (ObjectList<Masterable>::iterator it = ObjectList<Masterable>::begin(); it; ++it)
101            {
102                if (*it != this)
103                {
104                    if (it->myMaster_ == this)
105                    {
106                        orxout(internal_error) << this << " is still master in " << (*it) << endl;
107                        it->myMaster_ = 0;
108                    }
109
110                    while (true)
111                    {
112                        std::vector<Masterable*>::iterator it2 = std::find(it->slaves_.begin(), it->slaves_.end(), this);
113                        if (it2 != it->slaves_.end())
114                        {
115                            orxout(internal_error) << this << " is still slave in " << (*it) << endl;
116                            it->slaves_.erase(it2);
117                        }
118                        else
119                            break;
120                    }
121                }
122            }
123        }
124  }
125
126  void Masterable::XMLPort(Element& xmlelement, XMLPort::Mode mode)
127    {
128        SUPER(Masterable, XMLPort, xmlelement, mode);
129
130        XMLPortParam(Masterable, "formationFlight", setFormationFlight, getFormationFlight, xmlelement, mode).defaultValues(false);
131        XMLPortParam(Masterable, "formationSize", setFormationSize, getFormationSize, xmlelement, mode).defaultValues(STANDARD_MAX_FORMATION_SIZE);
132        XMLPortParam(Masterable, "passive", setPassive, getPassive, xmlelement, mode).defaultValues(false);
133    }
134
135
136
137  /**
138        @brief Activates / deactivates formationflight behaviour
139        @param form activate formflight if form is true
140    */
141  void Masterable::formationflight(const bool form)
142    {
143        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
144        {
145            Controller* controller = 0;
146
147            if (it->getController())
148                controller = it->getController();
149            else if (it->getXMLController())
150                controller = it->getXMLController();
151
152            if (!controller)
153                continue;
154
155            Masterable *aiController = orxonox_cast<Masterable*>(controller);
156
157            if (aiController)
158            {
159                aiController->formationFlight_ = form;
160                if (!form)
161                {
162                    aiController->removeFromFormation();
163                }
164            }
165        }
166    }
167
168  /**
169        @brief Get all masters to do a "specific master action"
170        @param action which action to perform (integer, so it can be called with a console command (tmp solution))
171    */
172    void Masterable::masteraction(const int action)
173    {
174        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
175        {
176            Controller* controller = 0;
177
178            if (it->getController())
179                controller = it->getController();
180            else if (it->getXMLController())
181                controller = it->getXMLController();
182
183            if (!controller)
184                continue;
185
186            Masterable *aiController = orxonox_cast<Masterable*>(controller);
187
188            if(aiController && aiController->state_ == MASTER)
189            {
190                if (action == 1)
191                    aiController->spinInit();
192                if (action == 2)
193                    aiController->turn180Init();
194            }
195        }
196    }
197
198  /**
199        @brief Sets shooting behaviour of pawns.
200        @param passive if true, bots won't shoot.
201    */
202    void Masterable::passivebehaviour(const bool passive)
203    {
204        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
205        {
206            Controller* controller = 0;
207
208            if (it->getController())
209                controller = it->getController();
210            else if (it->getXMLController())
211                controller = it->getXMLController();
212
213            if (!controller)
214                continue;
215
216            Masterable *aiController = orxonox_cast<Masterable*>(controller);
217
218            if(aiController)
219            {
220                aiController->passive_ = passive;
221            }
222        }
223    }
224
225  /**
226        @brief Sets maximal formation size
227        @param size maximal formation size.
228    */
229    void Masterable::formationsize(const int size)
230    {
231        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
232        {
233            Controller* controller = 0;
234
235            if (it->getController())
236                controller = it->getController();
237            else if (it->getXMLController())
238                controller = it->getXMLController();
239
240            if (!controller)
241                continue;
242
243            Masterable *aiController = orxonox_cast<Masterable*>(controller);
244
245            if(aiController)
246            {
247                aiController->maxFormationSize_ = size;
248            }
249        }
250    }
251
252  void Masterable::removeFromFormation()
253    {
254        if (this->state_ == SLAVE || this->myMaster_) // slaves can also be temporary free, so check if myMaster_ is set
255            this->unregisterSlave();
256        else if (this->state_ == MASTER)
257            this->setNewMasterWithinFormation();
258    }
259
260    void Masterable::moveToPosition(const Vector3& target)
261    {
262        if (!this->getControllableEntity())
263            return;
264
265        // Slave uses special movement if its master is in FOLLOW mode
266        if(this->state_ == SLAVE && this->myMaster_ && this->myMaster_->specificMasterAction_ == FOLLOW)
267        {
268//             this->followForSlaves(target);
269//             return;
270        }
271
272        Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, target);
273        float distance = (target - this->getControllableEntity()->getPosition()).length();
274
275
276        if(this->state_ == FREE)
277        {
278            if (this->target_ || distance > 10)
279            {
280                // Multiply with ROTATEFACTOR_FREE to make them a bit slower
281                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_FREE * sgn(coord.x) * coord.x*coord.x);
282                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_FREE * sgn(coord.y) * coord.y*coord.y);
283            }
284
285            if (this->target_ && distance < 200 && this->getControllableEntity()->getVelocity().squaredLength() > this->target_->getVelocity().squaredLength())
286            {
287              this->getControllableEntity()->moveFrontBack(-0.05f); // They don't brake with full power to give the player a chance
288            } else this->getControllableEntity()->moveFrontBack(SPEED_FREE);
289        }
290
291
292
293        if(this->state_ == MASTER)
294        {
295            if (this->target_ || distance > 10)
296            {
297                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_MASTER * sgn(coord.x) * coord.x*coord.x);
298                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_MASTER * sgn(coord.y) * coord.y*coord.y);
299            }
300
301            if (this->target_ && distance < 200 && this->getControllableEntity()->getVelocity().squaredLength() > this->target_->getVelocity().squaredLength())
302            {
303                this->getControllableEntity()->moveFrontBack(-0.05f);
304            } else this->getControllableEntity()->moveFrontBack(SPEED_MASTER);
305        }
306
307
308
309        if(this->state_ == SLAVE)
310        {
311
312           this->getControllableEntity()->rotateYaw(-2.0f * ROTATEFACTOR_MASTER * sgn(coord.x) * coord.x*coord.x);
313           this->getControllableEntity()->rotatePitch(2.0f * ROTATEFACTOR_MASTER * sgn(coord.y) * coord.y*coord.y);
314
315            if (distance < 300)
316            {
317                 if (bHasTargetOrientation_)
318                    {
319                        copyTargetOrientation();
320                    }
321                if (distance < 100)
322                {   //linear speed reduction
323                    this->getControllableEntity()->moveFrontBack(distance/100.0f*0.4f*SPEED_MASTER);
324                   
325                } else this->getControllableEntity()->moveFrontBack(1.2f*SPEED_MASTER);
326
327            } else {
328                this->getControllableEntity()->moveFrontBack(1.2f*SPEED_MASTER + distance/300.0f);
329            }
330        }
331
332        if (distance < 10)
333        {
334            this->positionReached();
335            bHasTargetOrientation_=false;
336        }
337    }
338
339
340
341  void Masterable::moveToTargetPosition()
342    {
343        this->moveToPosition(this->targetPosition_);
344    }
345
346  //copy the Roll orientation of given Quaternion.
347  void Masterable::copyOrientation(const Quaternion& orient)
348    {
349        //roll angle difference in radian
350        float diff=orient.getRoll(false).valueRadians()-(this->getControllableEntity()->getOrientation().getRoll(false).valueRadians());
351        while(diff>math::twoPi) diff-=math::twoPi;
352        while(diff<-math::twoPi) diff+=math::twoPi;
353        this->getControllableEntity()->rotateRoll(diff*ROTATEFACTOR_MASTER);
354    }
355
356    void Masterable::copyTargetOrientation()
357    {
358        if (bHasTargetOrientation_)
359        {
360            copyOrientation(targetOrientation_);
361        }
362    }
363
364
365   /**
366        @brief Unregisters a slave from its master. Initiated by a slave.
367    */
368    void Masterable::unregisterSlave()
369    {
370        if (this->myMaster_)
371        {
372            std::vector<Masterable*>::iterator it = std::find(this->myMaster_->slaves_.begin(), this->myMaster_->slaves_.end(), this);
373            if (it != this->myMaster_->slaves_.end())
374                this->myMaster_->slaves_.erase(it);
375        }
376
377        this->myMaster_ = 0;
378        this->state_ = FREE;
379    }
380
381    void Masterable::searchNewMaster()
382    {
383
384        if (!this->getControllableEntity())
385            return;
386
387        this->targetPosition_ = this->getControllableEntity()->getPosition();
388        this->forgetTarget();
389        int teamSize = 0;
390        //go through all pawns
391        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
392        {
393           
394            //same team?
395            Gametype* gt=this->getGametype();
396            if (!gt)
397            {
398                gt=it->getGametype();
399            }
400            if (!Masterable::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it),gt))
401                continue;
402
403            //has it an Masterable?
404            Controller* controller = 0;
405
406            if (it->getController())
407                controller = it->getController();
408            else if (it->getXMLController())
409                controller = it->getXMLController();
410
411            if (!controller)
412                continue;
413
414            //is pawn oneself?
415            if (orxonox_cast<ControllableEntity*>(*it) == this->getControllableEntity())
416                continue;
417
418            teamSize++;
419
420            Masterable *newMaster = orxonox_cast<Masterable*>(controller);
421
422            //is it a master?
423            if (!newMaster || newMaster->state_ != MASTER)
424                continue;
425
426            float distance = (it->getPosition() - this->getControllableEntity()->getPosition()).length();
427
428            // is pawn in range?
429            if (distance < RADIUS_TO_SEARCH_FOR_MASTERS)
430            {
431                if(newMaster->slaves_.size() > this->maxFormationSize_) continue;
432
433                for(std::vector<Masterable*>::iterator itSlave = this->slaves_.begin(); itSlave != this->slaves_.end(); itSlave++)
434                {
435                    (*itSlave)->myMaster_ = newMaster;
436                    newMaster->slaves_.push_back(*itSlave);
437                }
438                this->slaves_.clear();
439                this->state_ = SLAVE;
440
441                this->myMaster_ = newMaster;
442                newMaster->slaves_.push_back(this);
443
444                break;
445            }
446        }
447
448        if (this->state_ != SLAVE  && teamSize != 0)
449        {
450            this->state_ = MASTER;
451            this->myMaster_ = 0;
452        }
453    }
454 /**
455        @brief Commands the slaves of a master into a formation. Sufficiently fast not to be called within tick. Initiated by a master.
456    */
457
458void Masterable::commandSlaves()
459    {
460        if(this->state_ != MASTER) return;
461
462        Quaternion orient = this->getControllableEntity()->getOrientation();
463        Vector3 dest = this->getControllableEntity()->getPosition();
464
465        // 1 slave: follow
466        if (this->slaves_.size() == 1)
467        {
468            dest += 4*orient*WorldEntity::BACK;
469            this->slaves_.front()->setTargetPosition(dest);
470        }
471        else
472        // formation:
473        {
474            dest += 1.0f*orient*WorldEntity::BACK;
475            Vector3 pos = Vector3::ZERO;
476                 bool left=true;
477            int i = 1;
478           
479            for(std::vector<Masterable*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
480            {
481                pos = Vector3::ZERO;
482                if (left)
483                {
484                    pos+=dest+i*FORMATION_WIDTH*(orient*WorldEntity::LEFT);
485                } else{
486                    pos+=dest+i*FORMATION_WIDTH*(orient*WorldEntity::RIGHT);
487                    i++;
488                    dest+=FORMATION_LENGTH*(orient*WorldEntity::BACK);
489                }               
490                (*it)->setTargetOrientation(orient);
491                (*it)->setTargetPosition(pos);
492                left=!left;
493            }
494        }
495    }
496
497    /**
498        @brief Sets a new master within the formation. Called by a master.
499    */
500    void Masterable::setNewMasterWithinFormation()
501    {
502        if(this->state_ != MASTER) return;
503
504        if (!this->slaves_.empty())
505        {
506            Masterable *newMaster = this->slaves_.back();
507            this->slaves_.pop_back();
508
509            newMaster->state_ = MASTER;
510            newMaster->slaves_ = this->slaves_;
511            newMaster->myMaster_ = 0;
512
513            for(std::vector<Masterable*>::iterator it = newMaster->slaves_.begin(); it != newMaster->slaves_.end(); it++)
514            {
515                (*it)->myMaster_ = newMaster;
516            }
517        }
518
519        this->slaves_.clear();
520        this->specificMasterAction_ = NONE;
521        this->state_ = FREE;
522    }
523
524
525  /**
526        @brief Frees all slaves form a master. Initiated by a master.
527    */
528    void Masterable::freeSlaves()
529    {
530        if(this->state_ != MASTER) return;
531
532        for(std::vector<Masterable*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
533        {
534            (*it)->state_ = FREE;
535            (*it)->myMaster_ = 0;
536        }
537        this->slaves_.clear();
538    }
539
540    /**
541        @brief Master sets its slaves free for @ref FREEDOM_COUNT seconds.
542    */
543    void Masterable::forceFreeSlaves()
544    {
545        if(this->state_ != MASTER) return;
546
547        for(std::vector<Masterable*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
548        {
549            (*it)->state_ = FREE;
550            (*it)->forceFreedom();
551            (*it)->targetPosition_ = this->targetPosition_;
552            (*it)->bShooting_ = true;
553//             (*it)->getControllableEntity()->fire(0);// fire once for fun
554        }
555    }
556
557    void Masterable::loseMasterState()
558    {
559        this->freeSlaves();
560        this->state_ = FREE;
561    }
562
563
564    void Masterable::forceFreedom()
565    {
566        this->freedomCount_ = FREEDOM_COUNT;
567    }
568
569    /**
570        @brief Checks wether caller has been forced free, decrements time to stay forced free.
571        @return true if forced free.
572    */
573    bool Masterable::forcedFree()
574    {
575        if(this->freedomCount_ > 0)
576        {
577            this->freedomCount_--;
578            return true;
579        } else return false;
580    }
581
582
583    /**
584        @brief Call to take the lead of formation (if free, become slave of nearest formation, then, if Slave, become Master)
585    */
586    void Masterable::takeLeadOfFormation()
587    {
588        if (!this->getControllableEntity())
589            return;
590
591        if (this->state_==MASTER) return;
592        //search new Master, then take lead
593        if (this->state_==FREE)
594        {
595          searchNewMaster();
596        }
597
598        if (this->state_==SLAVE)  //become master of this formation
599        {   
600            this->slaves_=myMaster_->slaves_;
601            this->myMaster_->slaves_.clear();
602            this->myMaster_->state_=SLAVE;
603            this->myMaster_->myMaster_=this;
604           
605            //delete myself in slavelist
606            std::vector<Masterable*>::iterator it2 = std::find(this->slaves_.begin(), this->slaves_.end(), this);
607            if (it2 != this->slaves_.end())
608            {
609                 this->slaves_.erase(it2);
610            }
611            //add previous master
612            this->slaves_.push_back(this->myMaster_);
613            //set this as new master
614            for(std::vector<Masterable*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
615            {
616                 (*it)->myMaster_=this;
617            }
618            this->myMaster_=0;
619            this->state_=MASTER;
620        }
621        /*/debug
622        if (this->state_==SLAVE)
623           {orxout(debug_output) << this << " is slave "<< endl;}
624        else if (this->state_==MASTER)
625           {orxout(debug_output) << this << " is now a master of "<<this->slaves_.size()<<" slaves."<< endl;}
626        if (this->state_==FREE)
627           {orxout(debug_output) << this << " is free "<< endl;}*/
628    }
629
630    void Masterable::masterAttacked(Pawn* originator)
631    {
632       orxout(debug_output)<<"slaves, attack!"<<endl;
633       unsigned int i=0;
634       for(std::vector<Masterable*>::reverse_iterator it = slaves_.rbegin(); it != slaves_.rend(); it++)
635       {
636           if ((*it)->state_!=FREE)
637           {
638               (*it)->state_=FREE;
639               (*it)->forceFreedom();
640               (*it)->target_=originator;
641           }
642           i++;
643           if (i==slaves_.size()/2) break; //half the formation should attack.
644       }
645    }     
646
647
648    /**
649      @brief Sets the new mode. If master, set it for all slaves.
650    */
651    void Masterable::setMode(Mode val)
652    {
653        this->mode_=val;
654        if (this->state_==MASTER)
655        {
656            for(std::vector<Masterable*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
657            {
658                 (*it)->mode_=val;
659                 if (val==ATTACK)
660                     (*it)->forgetTarget();
661            }
662        }
663    }
664
665    /**
666        @brief Used to continue a "specific master action" for a certain time and resuming normal behaviour after.
667    */
668    void Masterable::specificMasterActionHold()
669    {
670        if(this->state_ != MASTER) return;
671
672        if (specificMasterActionHoldCount_ == 0)
673         {
674            this->specificMasterAction_ = NONE;
675            this->searchNewTarget();
676         }
677        else specificMasterActionHoldCount_--;
678    }
679
680    /**
681        @brief Master initializes a 180 degree turn. Leads to a "specific master action".
682    */
683    void Masterable::turn180Init()
684    {
685        if(this->state_ != MASTER) return;
686
687        Quaternion orient = this->getControllableEntity()->getOrientation();
688
689        this->setTargetPosition(this->getControllableEntity()->getPosition() + 1000.0f*orient*WorldEntity::BACK);
690
691        this->specificMasterActionHoldCount_ = 4;
692
693        this->specificMasterAction_ = TURN180;
694    }
695
696    /**
697        @brief Execute the 180 degree turn. Called within tick.
698    */
699    void Masterable::turn180()
700    {
701            Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, this->targetPosition_);
702
703            this->getControllableEntity()->rotateYaw(-2.0f * sgn(coord.x) * coord.x*coord.x);
704            this->getControllableEntity()->rotatePitch(2.0f * sgn(coord.y) * coord.y*coord.y);
705
706            this->getControllableEntity()->moveFrontBack(SPEED_MASTER);
707    }
708
709    /**
710        @brief Master initializes a spin around its looking direction axis. Leads to a "specific master action".
711    */
712    void Masterable::spinInit()
713    {
714        if(this->state_ != MASTER) return;
715        this->specificMasterAction_ = SPIN;
716        this->specificMasterActionHoldCount_ = 10;
717    }
718
719    /**
720        @brief Execute the spin. Called within tick.
721    */
722    void Masterable::spin()
723    {
724            this->moveToTargetPosition();
725            this->getControllableEntity()->rotateRoll(0.8f);
726    }
727
728  /**
729        @brief A human player gets followed by its nearest master. Initiated by console command, so far intended for demonstration puproses (possible future pickup).
730    */
731    void Masterable::followme()
732    {
733
734        Pawn *humanPawn = NULL;
735        NewHumanController *currentHumanController = NULL;
736        std::vector<Masterable*> allMasters;
737
738        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
739        {
740            Controller* controller = 0;
741
742            if (it->getController())
743                controller = it->getController();
744            else if (it->getXMLController())
745                controller = it->getXMLController();
746
747            if (!controller)
748                continue;
749
750            currentHumanController = orxonox_cast<NewHumanController*>(controller);
751
752            if(currentHumanController) humanPawn = *it;
753
754            Masterable *aiController = orxonox_cast<Masterable*>(controller);
755
756            if(aiController && aiController->state_ == MASTER)
757                allMasters.push_back(aiController);
758
759        }
760
761        if((humanPawn != NULL) && (allMasters.size() != 0))
762        {
763                float posHuman = humanPawn->getPosition().length();
764                float distance = 0.0f;
765                float minDistance = FLT_MAX;
766                int index = 0;
767                int i = 0;
768
769                for(std::vector<Masterable*>::iterator it = allMasters.begin(); it != allMasters.end(); it++, i++)
770                    {
771                        if (!Masterable::sameTeam((*it)->getControllableEntity(), humanPawn, (*it)->getGametype())) continue;
772                        distance = posHuman - (*it)->getControllableEntity()->getPosition().length();
773                        if(distance < minDistance) index = i;
774                    }
775                allMasters[index]->followInit(humanPawn);
776            }
777
778    }
779
780
781
782
783
784    /**
785        @brief Master begins to follow a pawn. Is a "specific master action".
786        @param pawn pawn to follow.
787        @param always follows pawn forever if true (false if omitted).
788        @param secondsToFollow seconds to follow the pawn if always is false. Will follow pawn 100 seconds if omitted (set in header).
789    */
790    void Masterable::followInit(Pawn* pawn, const bool always, const int secondsToFollow)
791    {
792        if (pawn == NULL || this->state_ != MASTER)
793            return;
794        this->specificMasterAction_  =  FOLLOW;
795
796        this->setTarget(pawn);
797        if (!always)
798            this->specificMasterActionHoldCount_ = secondsToFollow;
799        else
800            this->specificMasterActionHoldCount_ = INT_MAX; //for now...
801
802    }
803
804   /**
805        @brief Master begins to follow a randomly chosen human player of the same team. Is a "specific master action".
806    */
807    void Masterable::followRandomHumanInit()
808    {
809
810        Pawn *humanPawn = NULL;
811        NewHumanController *currentHumanController = NULL;
812
813        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
814        {
815            if (!it->getController())
816                continue;
817
818            currentHumanController = orxonox_cast<NewHumanController*>(it->getController());
819            if(currentHumanController)
820            {
821                if (!Masterable::sameTeam(this->getControllableEntity(), *it, this->getGametype())) continue;
822                humanPawn = *it;
823                break;
824            }
825        }
826
827        if((humanPawn != NULL))
828                this->followInit(humanPawn);
829    }
830
831
832  /**
833        @brief Master follows target with adjusted speed. Called within tick.
834    */
835    void Masterable::follow()
836    {
837        if (this->target_)
838            this->moveToPosition(this->target_->getPosition());
839        else
840            this->specificMasterActionHoldCount_ = 0;
841    }
842
843
844  void Masterable::setTargetPosition(const Vector3& target)
845    {
846        this->targetPosition_ = target;
847        this->bHasTargetPosition_ = true;
848    }
849
850    void Masterable::searchRandomTargetPosition()
851    {
852        this->targetPosition_ = Vector3(rnd(-2000,2000), rnd(-2000,2000), rnd(-2000,2000));
853        this->bHasTargetPosition_ = true;
854    }
855
856    void Masterable::setTargetOrientation(const Quaternion& orient)
857    {
858        this->targetOrientation_=orient;       
859        this->bHasTargetOrientation_=true;
860    }
861
862    void Masterable::setTargetOrientation(Pawn* target)
863    {
864        if (target)
865            setTargetOrientation(target->getOrientation());
866    }
867
868    void Masterable::setTarget(Pawn* target)
869    {
870        this->target_ = target;
871
872        if (target)
873            this->targetPosition_ = target->getPosition();
874    }
875
876    void Masterable::searchNewTarget()
877    {
878        if (!this->getControllableEntity())
879            return;
880
881        this->targetPosition_ = this->getControllableEntity()->getPosition();
882        this->forgetTarget();
883
884        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
885        {
886            if (Masterable::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it), this->getGametype()))
887                continue;
888
889            /* So AI won't choose invisible Spaceships as target */
890            if (!it->getRadarVisibility())
891                continue;
892
893            if (static_cast<ControllableEntity*>(*it) != this->getControllableEntity())
894            {
895                float speed = this->getControllableEntity()->getVelocity().length();
896                Vector3 distanceCurrent = this->targetPosition_ - this->getControllableEntity()->getPosition();
897                Vector3 distanceNew = it->getPosition() - this->getControllableEntity()->getPosition();
898                if (!this->target_ || it->getPosition().squaredDistance(this->getControllableEntity()->getPosition()) * (1.5f + acos((this->getControllableEntity()->getOrientation() * WorldEntity::FRONT).dotProduct(distanceNew) / speed / distanceNew.length()) / math::twoPi)
899                        < this->targetPosition_.squaredDistance(this->getControllableEntity()->getPosition()) * (1.5f + acos((this->getControllableEntity()->getOrientation() * WorldEntity::FRONT).dotProduct(distanceCurrent) / speed / distanceCurrent.length()) / math::twoPi) + rnd(-250, 250))
900                {
901                    this->target_ = (*it);
902                    this->targetPosition_ = it->getPosition();
903                }
904            }
905        }
906    }
907
908  void Masterable::forgetTarget()
909    {
910        this->target_ = 0;
911        this->bShooting_ = false;
912    }
913
914   void Masterable::targetDied()
915    {
916        this->forgetTarget();
917        this->searchRandomTargetPosition();
918    }
919
920  bool Masterable::sameTeam(ControllableEntity* entity1, ControllableEntity* entity2, Gametype* gametype)
921    {
922        if (entity1 == entity2)
923            return true;
924
925        int team1 = -1;
926        int team2 = -1;
927
928        Controller* controller = 0;
929        if (entity1->getController())
930            controller = entity1->getController();
931        else
932            controller = entity1->getXMLController();
933        if (controller)
934        {
935            Masterable* ac = orxonox_cast<Masterable*>(controller);
936            if (ac)
937                team1 = ac->getTeam();
938        }
939
940        if (entity2->getController())
941            controller = entity2->getController();
942        else
943            controller = entity2->getXMLController();
944        if (controller)
945        {
946            Masterable* ac = orxonox_cast<Masterable*>(controller);
947            if (ac)
948                team2 = ac->getTeam();
949        }
950
951        TeamDeathmatch* tdm = orxonox_cast<TeamDeathmatch*>(gametype);
952        if (tdm)
953        {
954            if (entity1->getPlayer())
955                team1 = tdm->getTeam(entity1->getPlayer());
956
957            if (entity2->getPlayer())
958                team2 = tdm->getTeam(entity2->getPlayer());
959        }
960
961        TeamBaseMatchBase* base = 0;
962        base = orxonox_cast<TeamBaseMatchBase*>(entity1);
963        if (base)
964        {
965            switch (base->getState())
966            {
967                case BaseState::ControlTeam1:
968                    team1 = 0;
969                    break;
970                case BaseState::ControlTeam2:
971                    team1 = 1;
972                    break;
973                case BaseState::Uncontrolled:
974                default:
975                    team1 = -1;
976            }
977        }
978        base = orxonox_cast<TeamBaseMatchBase*>(entity2);
979        if (base)
980        {
981            switch (base->getState())
982            {
983                case BaseState::ControlTeam1:
984                    team2 = 0;
985                    break;
986                case BaseState::ControlTeam2:
987                    team2 = 1;
988                    break;
989                case BaseState::Uncontrolled:
990                default:
991                    team2 = -1;
992            }
993        }
994
995        DroneController* droneController = 0;
996        droneController = orxonox_cast<DroneController*>(entity1->getController());
997        if (droneController && static_cast<ControllableEntity*>(droneController->getOwner()) == entity2)
998            return true;
999        droneController = orxonox_cast<DroneController*>(entity2->getController());
1000        if (droneController && static_cast<ControllableEntity*>(droneController->getOwner()) == entity1)
1001            return true;
1002        DroneController* droneController1 = orxonox_cast<DroneController*>(entity1->getController());
1003        DroneController* droneController2 = orxonox_cast<DroneController*>(entity2->getController());
1004        if (droneController1 && droneController2 && droneController1->getOwner() == droneController2->getOwner())
1005            return true;
1006
1007        Dynamicmatch* dynamic = orxonox_cast<Dynamicmatch*>(gametype);
1008        if (dynamic)
1009        {
1010            if (dynamic->notEnoughPigs||dynamic->notEnoughKillers||dynamic->notEnoughChasers) {return false;}
1011
1012            if (entity1->getPlayer())
1013                team1 = dynamic->getParty(entity1->getPlayer());
1014
1015            if (entity2->getPlayer())
1016                team2 = dynamic->getParty(entity2->getPlayer());
1017
1018            if (team1 ==-1 ||team2 ==-1 ) {return false;}
1019            else if (team1 == dynamic->chaser && team2 != dynamic->chaser) {return false;}
1020            else if (team1 == dynamic->piggy && team2 == dynamic->chaser) {return false;}
1021            else if (team1 == dynamic->killer && team2 == dynamic->chaser) {return false;}
1022            else return true;
1023        }
1024
1025        return (team1 == team2 && team1 != -1);
1026    }
1027
1028}
Note: See TracBrowser for help on using the repository browser.