Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/AI_HS15/src/orxonox/controllers/FormationController.cc @ 10670

Last change on this file since 10670 was 10670, checked in by gania, 9 years ago

hold position in formation with waypoints

  • Property svn:eol-style set to native
File size: 38.0 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 *      ...
24 *   Co-authors:
25 *      Dominik Solenicki
26 *
27 */
28
29#include <climits>
30#include "controllers/FormationController.h"
31
32#include "core/CoreIncludes.h"
33
34#include "core/XMLPort.h"
35#include "core/command/ConsoleCommandIncludes.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/Mission.h"
43#include "gametypes/Gametype.h"
44#include "controllers/WaypointPatrolController.h"
45#include "controllers/NewHumanController.h"
46#include "controllers/DroneController.h"
47
48
49namespace orxonox
50{
51
52    SetConsoleCommand("FormationController", "formationflight",  &FormationController::formationflight);
53    SetConsoleCommand("FormationController", "masteraction",     &FormationController::masteraction);
54    SetConsoleCommand("FormationController", "followme",         &FormationController::followme);
55    SetConsoleCommand("FormationController", "passivebehaviour", &FormationController::passivebehaviour);
56    SetConsoleCommand("FormationController", "formationsize",    &FormationController::formationsize);
57
58    RegisterClass(FormationController);
59
60    static const unsigned int STANDARD_MAX_FORMATION_SIZE = 9;
61    static const int RADIUS_TO_SEARCH_FOR_MASTERS = 5000;
62    static const float FORMATION_LENGTH =  110;
63    static const float 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    FormationController::FormationController(Context* context) : Controller(context)
71    {
72        RegisterObject(FormationController);
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->formationMode_ = 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->target_.setCallback(createFunctor(&FormationController::targetDied, this));
91    }
92
93    FormationController::~FormationController()
94    {
95        if (this->isInitialized())
96        {
97            this->removeFromFormation();
98
99            for (ObjectList<FormationController>::iterator it = ObjectList<FormationController>::begin(); it; ++it)
100            {
101                if (*it != this)
102                {
103                    if (it->myMaster_ == this)
104                    {
105                        orxout(internal_error) << this << " is still master in " << (*it) << endl;
106                        it->myMaster_ = 0;
107                        it->state_ = FREE;
108                    }
109
110                    while (true)
111                    {
112                        std::vector<FormationController*>::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 FormationController::XMLPort(Element& xmlelement, XMLPort::Mode mode)
127    {
128        SUPER(FormationController, XMLPort, xmlelement, mode);
129
130        XMLPortParam(FormationController, "formationFlight", setFormationFlight, getFormationFlight, xmlelement, mode).defaultValues(false);
131        XMLPortParam(FormationController, "formationSize", setFormationSize, getFormationSize, xmlelement, mode).defaultValues(STANDARD_MAX_FORMATION_SIZE);
132        XMLPortParam(FormationController, "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 FormationController::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            FormationController *aiController = orxonox_cast<FormationController*>(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 FormationController::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            FormationController *aiController = orxonox_cast<FormationController*>(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 FormationController::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            FormationController *aiController = orxonox_cast<FormationController*>(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 FormationController::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            FormationController *aiController = orxonox_cast<FormationController*>(controller);
244
245            if(aiController)
246            {
247                aiController->maxFormationSize_ = size;
248            }
249        }
250    }
251
252    //used, when slaves are in DEFEND mode.
253    void FormationController::hit(Pawn* originator, btManifoldPoint& contactpoint, float damage)
254    {
255        if (!this->formationFlight_ || this->state_ != MASTER || this->formationMode_ != DEFEND)
256            return;
257        this->masterAttacked(originator);
258    }
259
260    void FormationController::removeFromFormation()
261    {
262        if (this->state_ == SLAVE || this->myMaster_) // slaves can also be temporary free, so check if myMaster_ is set
263            this->unregisterSlave();
264        else if (this->state_ == MASTER)
265            this->setNewMasterWithinFormation();
266    }
267
268    void FormationController::moveToPosition(const Vector3& target)
269    {
270        if (!this->getControllableEntity())
271            return;
272
273        // Slave uses special movement if its master is in FOLLOW mode
274        if(this->state_ == SLAVE && this->myMaster_ && this->myMaster_->specificMasterAction_ == FOLLOW)
275        {
276//             this->followForSlaves(target);
277//             return;
278        }
279
280        Vector2 coord = get2DViewCoordinates(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, target);
281        float distance = (target - this->getControllableEntity()->getPosition()).length();
282        float rotateX = clamp(coord.x * 10, -1.0f, 1.0f);
283        float rotateY = clamp(coord.y * 10, -1.0f, 1.0f);
284
285        if(this->state_ == FREE)
286        {
287            if (this->target_ || distance > 10)
288            {
289                // Multiply with ROTATEFACTOR_FREE to make them a bit slower
290                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_FREE * rotateX);
291                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_FREE * rotateY);
292            }
293
294            if (this->target_ && distance <  200 && this->getControllableEntity()->getVelocity().squaredLength() > this->target_->getVelocity().squaredLength())
295            {
296              this->getControllableEntity()->moveFrontBack(-0.05f); // They don't brake with full power to give the player a chance
297            } else this->getControllableEntity()->moveFrontBack(SPEED_FREE);
298        }
299
300
301
302        if(this->state_ == MASTER)
303        {
304            if (this->target_ || distance > 10)
305            {
306                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_MASTER * rotateX);
307                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_MASTER * rotateY);
308            }
309
310            if (this->target_ && distance < 200 && this->getControllableEntity()->getVelocity().squaredLength() > this->target_->getVelocity().squaredLength())
311            {
312                this->getControllableEntity()->moveFrontBack(-0.05f);
313            } else this->getControllableEntity()->moveFrontBack(SPEED_MASTER);
314        }
315
316
317
318        if(this->state_ == SLAVE)
319        {
320
321            this->getControllableEntity()->rotateYaw(-2.0f * ROTATEFACTOR_MASTER * rotateX);
322            this->getControllableEntity()->rotatePitch(2.0f * ROTATEFACTOR_MASTER * rotateY);
323
324            if (distance < 300)
325            {
326                if (bHasTargetOrientation_)
327                {
328                    copyTargetOrientation();
329                }
330                if (distance < 100)
331                { //linear speed reduction
332                    this->getControllableEntity()->moveFrontBack(distance/100.0f*0.4f*SPEED_MASTER);
333                }
334                else
335                    this->getControllableEntity()->moveFrontBack(1.2f*SPEED_MASTER);
336            }
337            else
338                this->getControllableEntity()->moveFrontBack(1.2f*SPEED_MASTER + distance/300.0f);
339        }
340
341        if (distance < 10)
342        {
343            this->positionReached();
344            bHasTargetOrientation_=false;
345        }
346    }
347
348
349
350    void FormationController::moveToTargetPosition()
351    {
352        this->moveToPosition(this->targetPosition_);
353    }
354
355    //copy the Roll orientation of given Quaternion.
356    void FormationController::copyOrientation(const Quaternion& orient)
357    {
358        //roll angle difference in radian
359        float diff=orient.getRoll(false).valueRadians()-(this->getControllableEntity()->getOrientation().getRoll(false).valueRadians());
360        while(diff>math::twoPi) diff-=math::twoPi;
361        while(diff<-math::twoPi) diff+=math::twoPi;
362        this->getControllableEntity()->rotateRoll(diff*ROTATEFACTOR_MASTER);
363    }
364
365    void FormationController::copyTargetOrientation()
366    {
367        if (bHasTargetOrientation_)
368        {
369            copyOrientation(targetOrientation_);
370        }
371    }
372
373
374    /**
375        @brief Unregisters a slave from its master. Initiated by a slave.
376    */
377    void FormationController::unregisterSlave()
378    {
379        if (this->myMaster_)
380        {
381            std::vector<FormationController*>::iterator it = std::find(this->myMaster_->slaves_.begin(), this->myMaster_->slaves_.end(), this);
382            if (it != this->myMaster_->slaves_.end())
383                this->myMaster_->slaves_.erase(it);
384        }
385
386        this->myMaster_ = 0;
387        this->state_ = FREE;
388    }
389
390    void FormationController::searchNewMaster()
391    {
392        if (this->state_==SLAVE)
393           return;
394        if (!this->getControllableEntity())
395            return;
396
397        this->targetPosition_ = this->getControllableEntity()->getPosition();
398        this->forgetTarget();
399        int teamSize = 0;
400        //go through all pawns
401        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
402        {
403
404            //same team?
405            Gametype* gt=this->getGametype();
406            if (!gt)
407            {
408                gt=it->getGametype();
409            }
410            if (!FormationController::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it),gt))
411                continue;
412
413            //has it an FormationController?
414            Controller* controller = 0;
415
416            if (it->getController())
417                controller = it->getController();
418            else if (it->getXMLController())
419                controller = it->getXMLController();
420
421            if (!controller)
422                continue;
423
424            //is pawn oneself?
425            if (orxonox_cast<ControllableEntity*>(*it) == this->getControllableEntity())
426                continue;
427
428            teamSize++;
429
430            FormationController *newMaster = orxonox_cast<FormationController*>(controller);
431
432            //is it a master?
433            if (!newMaster || newMaster->state_ != MASTER)
434                continue;
435
436            float distance = (it->getPosition() - this->getControllableEntity()->getPosition()).length();
437
438            // is pawn in range?
439            if (distance < RADIUS_TO_SEARCH_FOR_MASTERS)
440            {
441                if(newMaster->slaves_.size() > this->maxFormationSize_) continue;
442
443                for(std::vector<FormationController*>::iterator itSlave = this->slaves_.begin(); itSlave != this->slaves_.end(); itSlave++)
444                {
445                    (*itSlave)->myMaster_ = newMaster;
446                    newMaster->slaves_.push_back(*itSlave);
447                }
448                this->slaves_.clear();
449                this->state_ = SLAVE;
450
451                this->myMaster_ = newMaster;
452                newMaster->slaves_.push_back(this);
453
454                break;
455            }
456        }
457
458        if (this->state_ != SLAVE  && teamSize != 0)
459        {
460            this->state_ = MASTER;
461            this->myMaster_ = 0;
462        }
463    }
464
465    /**
466        @brief Commands the slaves of a master into a formation. Sufficiently fast not to be called within tick. Initiated by a master.
467    */
468    void FormationController::commandSlaves()
469    {
470        if(this->state_ != MASTER) return;
471
472        Quaternion orient = this->getControllableEntity()->getOrientation();
473        Vector3 dest = this->getControllableEntity()->getPosition();
474
475        // only 1 slave: follow
476        if (this->slaves_.size() == 1)
477        {
478            dest += 4*orient*WorldEntity::BACK;
479            this->slaves_.front()->setTargetPosition(dest);
480        }
481        else
482        // formation:
483        {
484            dest += 1.0f*orient*WorldEntity::BACK;
485            Vector3 pos = Vector3::ZERO;
486            bool left=true;
487            int i = 1;
488
489            for(std::vector<FormationController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
490            {
491                pos = Vector3::ZERO;
492                if (left)
493                {
494                    pos+=dest+i*FORMATION_WIDTH*(orient*WorldEntity::LEFT);
495                } else{
496                    pos+=dest+i*FORMATION_WIDTH*(orient*WorldEntity::RIGHT);
497                    i++;
498                    dest+=FORMATION_LENGTH*(orient*WorldEntity::BACK);
499                }
500                (*it)->setTargetOrientation(orient);
501                (*it)->setTargetPosition(pos);
502                left=!left;
503            }
504        }
505    }
506
507    /**
508        @brief Sets a new master within the formation. Called by a master.
509    */
510    void FormationController::setNewMasterWithinFormation()
511    {
512        if(this->state_ != MASTER) return;
513
514        if (!this->slaves_.empty())
515        {
516            FormationController *newMaster = this->slaves_.back();
517            this->slaves_.pop_back();
518
519            newMaster->state_ = MASTER;
520            newMaster->slaves_ = this->slaves_;
521            newMaster->myMaster_ = 0;
522
523            for(std::vector<FormationController*>::iterator it = newMaster->slaves_.begin(); it != newMaster->slaves_.end(); it++)
524            {
525                (*it)->myMaster_ = newMaster;
526            }
527        }
528
529        this->slaves_.clear();
530        this->specificMasterAction_ = NONE;
531        this->state_ = FREE;
532    }
533
534
535    // Sets newMaster as the new master within the formation. Called by the master.
536    void FormationController::setNewMasterWithinFormation(FormationController* newMaster)
537        {
538            if(this->state_ != MASTER || newMaster->myMaster_ != this) return;
539
540            if (!this->slaves_.empty())
541            {
542                std::vector<FormationController*>::iterator it2 = std::find(this->slaves_.begin(), this->slaves_.end(), newMaster);
543                if (it2 != this->slaves_.end())
544                {
545                    this->slaves_.erase(it2);
546                }
547
548                newMaster->state_ = MASTER;
549                newMaster->slaves_ = this->slaves_;
550                newMaster->myMaster_ = 0;
551
552                for(std::vector<FormationController*>::iterator it = newMaster->slaves_.begin(); it != newMaster->slaves_.end(); it++)
553                {
554                    (*it)->myMaster_ = newMaster;
555                }
556            }
557
558            this->slaves_.clear();
559            this->specificMasterAction_ = NONE;
560            this->state_ = FREE;
561        }
562
563
564
565  /**
566        @brief Frees all slaves from a master. Initiated by a master.
567    */
568    void FormationController::freeSlaves()
569    {
570        if(this->state_ != MASTER) return;
571
572        for(std::vector<FormationController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
573        {
574            (*it)->state_ = FREE;
575            (*it)->myMaster_ = 0;
576        }
577        this->slaves_.clear();
578    }
579
580    /**
581        @brief Master sets its slaves free for @ref FREEDOM_COUNT seconds.
582    */
583    void FormationController::forceFreeSlaves()
584    {
585        if(this->state_ != MASTER) return;
586
587        for(std::vector<FormationController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
588        {
589            (*it)->state_ = FREE;
590            (*it)->forceFreedom();
591            (*it)->targetPosition_ = this->targetPosition_;
592            (*it)->bShooting_ = true;
593//             (*it)->getControllableEntity()->fire(0);// fire once for fun
594        }
595    }
596
597    void FormationController::loseMasterState()
598    {
599        this->freeSlaves();
600        this->state_ = FREE;
601    }
602
603
604    void FormationController::forceFreedom()
605    {
606        this->freedomCount_ = FREEDOM_COUNT;
607    }
608
609    /**
610        @brief Checks wether caller has been forced free, decrements time to stay forced free.
611        @return true if forced free.
612    */
613    bool FormationController::forcedFree()
614    {
615        if(this->freedomCount_ > 0)
616        {
617            this->freedomCount_--;
618            return true;
619        } else return false;
620    }
621
622
623    /**
624        @brief Call to take the lead of formation (if free, become slave of nearest formation, then, if Slave, become Master)
625    */
626    void FormationController::takeLeadOfFormation()
627    {
628        if (!this->getControllableEntity() || this->state_==MASTER)
629            return;
630
631        //search new Master, then take lead
632        if (this->state_==FREE && this->myMaster_==0)
633        {
634          searchNewMaster();
635        }
636
637        if (this->state_==SLAVE)  //become master of this formation
638        {
639            this->slaves_=this->myMaster_->slaves_;
640            this->myMaster_->slaves_.clear();
641            this->myMaster_->state_=SLAVE;
642            this->myMaster_->myMaster_=this;
643
644            //delete myself in slavelist
645            std::vector<FormationController*>::iterator it2 = std::find(this->slaves_.begin(), this->slaves_.end(), this);
646            if (it2 != this->slaves_.end())
647            {
648                 this->slaves_.erase(it2);
649            }
650            //add previous master
651            this->slaves_.push_back(this->myMaster_);
652            //set this as new master
653            for(std::vector<FormationController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
654            {
655                 (*it)->myMaster_=this;
656            }
657            this->myMaster_=0;
658            this->state_=MASTER;
659        }
660        /*/debug
661        if (this->state_==SLAVE)
662           {orxout(debug_output) << this << " is slave "<< endl;}
663        else if (this->state_==MASTER)
664           {orxout(debug_output) << this << " is now a master of "<<this->slaves_.size()<<" slaves."<< endl;}
665        if (this->state_==FREE)
666           {orxout(debug_output) << this << " is free "<< endl;}*/
667    }
668    /**
669      @brief if called, half of the formation will attack the originator
670    */
671    void FormationController::masterAttacked(Pawn* originator)
672    {
673       if (this->state_!=MASTER) return;
674       unsigned int i=0;
675       for(std::vector<FormationController*>::reverse_iterator it = slaves_.rbegin(); it != slaves_.rend(); it++)
676       {
677           if ((*it)->state_!=FREE)
678           {
679               (*it)->state_=FREE;
680               (*it)->forceFreedom();
681               (*it)->setTarget(originator);
682           }
683           i++;
684           if (i>=slaves_.size()/2) break; //half the formation should attack.
685       }
686    }
687
688
689    /**
690      @brief Sets the new mode. If master, set it for all slaves.
691    */
692    void FormationController::setFormationMode(FormationMode val)
693    {
694        this->formationMode_ = val;
695        if (this->state_ == MASTER)
696        {
697            for(std::vector<FormationController*>::iterator it = slaves_.begin(); it != slaves_.end(); it++)
698            {
699                 (*it)->formationMode_ = val;
700                 if (val == ATTACK)
701                     (*it)->forgetTarget();
702            }
703        }
704    }
705     /**
706      @brief If master, set the desired relative position of slaves (Vector3) in respect to a master for all the slaves.
707    */
708    void FormationController::setDesiredPositionOfSlaves()
709    {
710        if (this->state_ != MASTER)
711            return;
712        switch (this->formationMode_){
713            case ATTACK:
714            for(std::vector<FormationController*>::iterator it = slaves_.begin(), float i = 0; it != slaves_.end(); it++, ++i)
715            {
716                (*it)->desiredPosition_ = new Vector3 ((i-slaves_.size()/2)*200, 0, 0);
717               
718            }
719            break;
720            case NORMAL:
721
722            break;
723            case DEFEND:
724
725            break;
726        }
727       
728    }
729
730    /**
731        @brief Used to continue a "specific master action" for a certain time and resuming normal behaviour after.
732    */
733    void FormationController::specificMasterActionHold()
734    {
735        if(this->state_ != MASTER) return;
736
737        if (specificMasterActionHoldCount_ == 0)
738        {
739            this->specificMasterAction_ = NONE;
740            this->searchNewTarget();
741        }
742        else
743            specificMasterActionHoldCount_--;
744    }
745
746    /**
747        @brief Master initializes a 180 degree turn. Leads to a "specific master action".
748    */
749    void FormationController::turn180Init()
750    {
751        if(this->state_ != MASTER) return;
752
753        Quaternion orient = this->getControllableEntity()->getOrientation();
754
755        this->setTargetPosition(this->getControllableEntity()->getPosition() + 1000.0f*orient*WorldEntity::BACK);
756
757        this->specificMasterActionHoldCount_ = 4;
758
759        this->specificMasterAction_ = TURN180;
760    }
761
762    /**
763        @brief Execute the 180 degree turn. Called within tick.
764    */
765    void FormationController::turn180()
766    {
767        Vector2 coord = get2DViewdirection(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, this->targetPosition_);
768
769        this->getControllableEntity()->rotateYaw(-2.0f * sgn(coord.x) * coord.x*coord.x);
770        this->getControllableEntity()->rotatePitch(2.0f * sgn(coord.y) * coord.y*coord.y);
771
772        this->getControllableEntity()->moveFrontBack(SPEED_MASTER);
773    }
774
775    /**
776        @brief Master initializes a spin around its looking direction axis. Leads to a "specific master action".
777    */
778    void FormationController::spinInit()
779    {
780        if(this->state_ != MASTER) return;
781        this->specificMasterAction_ = SPIN;
782        this->specificMasterActionHoldCount_ = 10;
783    }
784
785    /**
786        @brief Execute the spin. Called within tick.
787    */
788    void FormationController::spin()
789    {
790        this->moveToTargetPosition();
791        this->getControllableEntity()->rotateRoll(0.8f);
792    }
793
794  /**
795        @brief A human player gets followed by its nearest master. Initiated by console command, so far intended for demonstration puproses (possible future pickup).
796    */
797    void FormationController::followme()
798    {
799
800        Pawn *humanPawn = NULL;
801        NewHumanController *currentHumanController = NULL;
802        std::vector<FormationController*> allMasters;
803
804        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
805        {
806            Controller* controller = 0;
807
808            if (it->getController())
809                controller = it->getController();
810            else if (it->getXMLController())
811                controller = it->getXMLController();
812
813            if (!controller)
814                continue;
815
816            currentHumanController = orxonox_cast<NewHumanController*>(controller);
817
818            if(currentHumanController) humanPawn = *it;
819
820            FormationController *aiController = orxonox_cast<FormationController*>(controller);
821
822            if(aiController && aiController->state_ == MASTER)
823                allMasters.push_back(aiController);
824
825        }
826
827        if((humanPawn != NULL) && (allMasters.size() != 0))
828        {
829            float posHuman = humanPawn->getPosition().length();
830            float distance = 0.0f;
831            float minDistance = FLT_MAX;
832            int index = 0;
833            int i = 0;
834
835            for(std::vector<FormationController*>::iterator it = allMasters.begin(); it != allMasters.end(); it++, i++)
836            {
837                if (!FormationController::sameTeam((*it)->getControllableEntity(), humanPawn, (*it)->getGametype())) continue;
838                distance = posHuman - (*it)->getControllableEntity()->getPosition().length();
839                if(distance < minDistance) index = i;
840            }
841            allMasters[index]->followInit(humanPawn);
842        }
843    }
844
845    /**
846        @brief Master begins to follow a pawn. Is a "specific master action".
847        @param pawn pawn to follow.
848        @param always follows pawn forever if true (false if omitted).
849        @param secondsToFollow seconds to follow the pawn if always is false. Will follow pawn 100 seconds if omitted (set in header).
850    */
851    void FormationController::followInit(Pawn* pawn, const bool always, const int secondsToFollow)
852    {
853        if (pawn == NULL || this->state_ != MASTER)
854            return;
855        this->specificMasterAction_  =  FOLLOW;
856
857        this->setTarget(pawn);
858        if (!always)
859            this->specificMasterActionHoldCount_ = secondsToFollow;
860        else
861            this->specificMasterActionHoldCount_ = INT_MAX; //for now...
862
863    }
864
865    /**
866        @brief Master begins to follow a randomly chosen human player of the same team. Is a "specific master action".
867    */
868    void FormationController::followRandomHumanInit()
869    {
870
871        Pawn *humanPawn = NULL;
872        NewHumanController *currentHumanController = NULL;
873
874        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
875        {
876            if (!it->getController())
877                continue;
878
879            currentHumanController = orxonox_cast<NewHumanController*>(it->getController());
880            if(currentHumanController)
881            {
882                if (!FormationController::sameTeam(this->getControllableEntity(), *it, this->getGametype())) continue;
883                humanPawn = *it;
884                break;
885            }
886        }
887
888        if((humanPawn != NULL))
889                this->followInit(humanPawn);
890    }
891
892
893    /**
894        @brief Master follows target with adjusted speed. Called within tick.
895    */
896    void FormationController::follow()
897    {
898        if (this->target_)
899            this->moveToPosition(this->target_->getPosition());
900        else
901            this->specificMasterActionHoldCount_ = 0;
902    }
903
904
905    void FormationController::setTargetPosition(const Vector3& target)
906    {
907        this->targetPosition_ = target;
908        this->bHasTargetPosition_ = true;
909    }
910
911    void FormationController::searchRandomTargetPosition()
912    {
913        this->targetPosition_ = Vector3(rnd(-2000,2000), rnd(-2000,2000), rnd(-2000,2000));
914        this->bHasTargetPosition_ = true;
915    }
916
917    void FormationController::setTargetOrientation(const Quaternion& orient)
918    {
919        this->targetOrientation_=orient;
920        this->bHasTargetOrientation_=true;
921    }
922
923    void FormationController::setTargetOrientation(Pawn* target)
924    {
925        if (target)
926            setTargetOrientation(target->getOrientation());
927    }
928
929    void FormationController::setTarget(Pawn* target)
930    {
931        this->target_ = target;
932
933        if (target)
934            this->targetPosition_ = target->getPosition();
935    }
936
937    void FormationController::searchNewTarget()
938    {
939        if (!this->getControllableEntity())
940            return;
941
942        this->targetPosition_ = this->getControllableEntity()->getPosition();
943        this->forgetTarget();
944
945        for (ObjectList<Pawn>::iterator it = ObjectList<Pawn>::begin(); it; ++it)
946        {
947            if (FormationController::sameTeam(this->getControllableEntity(), static_cast<ControllableEntity*>(*it), this->getGametype()))
948                continue;
949
950            /* So AI won't choose invisible Spaceships as target */
951            if (!it->getRadarVisibility())
952                continue;
953
954            if (static_cast<ControllableEntity*>(*it) != this->getControllableEntity())
955            {
956                float speed = this->getControllableEntity()->getVelocity().length();
957                Vector3 distanceCurrent = this->targetPosition_ - this->getControllableEntity()->getPosition();
958                Vector3 distanceNew = it->getPosition() - this->getControllableEntity()->getPosition();
959                if (!this->target_ || it->getPosition().squaredDistance(this->getControllableEntity()->getPosition()) * (1.5f + acos((this->getControllableEntity()->getOrientation() * WorldEntity::FRONT).dotProduct(distanceNew) / speed / distanceNew.length()) / math::twoPi)
960                        < this->targetPosition_.squaredDistance(this->getControllableEntity()->getPosition()) * (1.5f + acos((this->getControllableEntity()->getOrientation() * WorldEntity::FRONT).dotProduct(distanceCurrent) / speed / distanceCurrent.length()) / math::twoPi) + rnd(-250, 250))
961                {
962                    this->setTarget(*it);
963                }
964            }
965        }
966    }
967
968    void FormationController::forgetTarget()
969    {
970        this->target_ = 0;
971        this->bShooting_ = false;
972    }
973
974    void FormationController::targetDied()
975    {
976        this->forgetTarget();
977        this->searchRandomTargetPosition();
978    }
979
980    bool FormationController::sameTeam(ControllableEntity* entity1, ControllableEntity* entity2, Gametype* gametype)
981    {
982
983
984        if (entity1 == entity2)
985            return true;
986
987        int team1 = entity1->getTeam();
988        int team2 = entity2->getTeam();
989
990        Controller* controller = 0;
991        if (entity1->getController())
992            controller = entity1->getController();
993        else
994            controller = entity1->getXMLController();
995        if (controller)
996        {
997            FormationController* ac = orxonox_cast<FormationController*>(controller);
998            if (ac)
999                team1 = ac->getTeam();
1000        }
1001
1002        if (entity2->getController())
1003            controller = entity2->getController();
1004        else
1005            controller = entity2->getXMLController();
1006        if (controller)
1007        {
1008            FormationController* ac = orxonox_cast<FormationController*>(controller);
1009            if (ac)
1010                team2 = ac->getTeam();
1011        }
1012
1013        TeamGametype* tdm = orxonox_cast<TeamGametype*>(gametype);
1014        if (tdm)
1015        {
1016            if (entity1->getPlayer())
1017                team1 = tdm->getTeam(entity1->getPlayer());
1018
1019            if (entity2->getPlayer())
1020                team2 = tdm->getTeam(entity2->getPlayer());
1021        }
1022
1023        TeamBaseMatchBase* base = 0;
1024        base = orxonox_cast<TeamBaseMatchBase*>(entity1);
1025        if (base)
1026        {
1027            switch (base->getState())
1028            {
1029                case BaseState::ControlTeam1:
1030                    team1 = 0;
1031                    break;
1032                case BaseState::ControlTeam2:
1033                    team1 = 1;
1034                    break;
1035                case BaseState::Uncontrolled:
1036                default:
1037                    team1 = -1;
1038            }
1039        }
1040        base = orxonox_cast<TeamBaseMatchBase*>(entity2);
1041        if (base)
1042        {
1043            switch (base->getState())
1044            {
1045                case BaseState::ControlTeam1:
1046                    team2 = 0;
1047                    break;
1048                case BaseState::ControlTeam2:
1049                    team2 = 1;
1050                    break;
1051                case BaseState::Uncontrolled:
1052                default:
1053                    team2 = -1;
1054            }
1055        }
1056
1057        DroneController* droneController = 0;
1058        droneController = orxonox_cast<DroneController*>(entity1->getController());
1059        if (droneController && static_cast<ControllableEntity*>(droneController->getOwner()) == entity2)
1060            return true;
1061        droneController = orxonox_cast<DroneController*>(entity2->getController());
1062        if (droneController && static_cast<ControllableEntity*>(droneController->getOwner()) == entity1)
1063            return true;
1064        DroneController* droneController1 = orxonox_cast<DroneController*>(entity1->getController());
1065        DroneController* droneController2 = orxonox_cast<DroneController*>(entity2->getController());
1066        if (droneController1 && droneController2 && droneController1->getOwner() == droneController2->getOwner())
1067            return true;
1068
1069        Dynamicmatch* dynamic = orxonox_cast<Dynamicmatch*>(gametype);
1070        if (dynamic)
1071        {
1072            if (dynamic->notEnoughPigs||dynamic->notEnoughKillers||dynamic->notEnoughChasers) {return false;}
1073
1074            if (entity1->getPlayer())
1075                team1 = dynamic->getParty(entity1->getPlayer());
1076
1077            if (entity2->getPlayer())
1078                team2 = dynamic->getParty(entity2->getPlayer());
1079
1080            if (team1 ==-1 ||team2 ==-1 ) {return false;}
1081            else if (team1 == dynamic->chaser && team2 != dynamic->chaser) {return false;}
1082            else if (team1 == dynamic->piggy && team2 == dynamic->chaser) {return false;}
1083            else if (team1 == dynamic->killer && team2 == dynamic->chaser) {return false;}
1084            else return true;
1085        }
1086
1087        return (team1 == team2 && team1 != -1);
1088    }
1089
1090    void FormationController::absoluteMoveToPosition(const Vector3& target)
1091    {
1092        float minDistance = 40.0f;
1093        if (!this->getControllableEntity())
1094            return;
1095
1096        Vector2 coord = get2DViewCoordinates(this->getControllableEntity()->getPosition(), this->getControllableEntity()->getOrientation() * WorldEntity::FRONT, this->getControllableEntity()->getOrientation() * WorldEntity::UP, target);
1097        float distance = (target - this->getControllableEntity()->getPosition()).length();
1098
1099            if (this->target_ || distance > minDistance)
1100            {
1101                // Multiply with ROTATEFACTOR_FREE to make them a bit slower
1102                this->getControllableEntity()->rotateYaw(-1.0f * ROTATEFACTOR_FREE * clamp(coord.x * 10, -1.0f, 1.0f));
1103                this->getControllableEntity()->rotatePitch(ROTATEFACTOR_FREE * clamp(coord.y * 10, -1.0f, 1.0f));
1104                this->getControllableEntity()->moveFrontBack(SPEED_FREE);
1105            }
1106
1107
1108        if (distance < minDistance)
1109        {
1110            this->positionReached();
1111        }
1112    }
1113
1114    void FormationController::changedControllableEntity()
1115    {
1116        Controller::changedControllableEntity(); // super
1117
1118        // when changing the controllable entity, ensure that the controller does not use the new entity as target
1119        if (this->target_ && this->getControllableEntity() == static_cast<ControllableEntity*>(this->target_))
1120            this->forgetTarget();
1121    }
1122}
Note: See TracBrowser for help on using the repository browser.