Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/AsteroidMining_HS17/src/modules/asteroidmining/AsteroidMinable.cc @ 11609

Last change on this file since 11609 was 11609, checked in by remartin, 6 years ago

Solved pickup problem with tiny adaptation in Pawn.h and PickupSpawner.cc. Started work on SpicedAsteroidField.

File size: 20.9 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 *      Simon Miescher
26 *
27 */
28
29/*
30
31*
32*
33* An asteroid which can be destroyed. Some smaller asteroids are created and a pickup
34* spawns.
35*
36*
37*
38
39*/
40
41/*
42Veraenderungstagebuch
43++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
44
45KNACKPUNKTE:
46
47OFFEN:
48o Add custom pickup 'resources'. Weird template stuff -> Problems setting 'size' and other properties? setNumber of Resources.
49--> PickupTemplateName_ in PickupSpawner ist ein string. Wird via getBaseClassIdentifier ausgelesen, daraus wird ein Pickupable fabriziert.
50--> MunitionPickup erbt von Pickup erbt von collectiblePickup erbt von Pickupable
51----> im MineralsPickup die isPickedUp()-Methode überschreiben?
52--> data_extern/images/effects: PNG's für die Pickups und GUI-Dinger.
53
54o Explosion parts
55o custom HUD
56o asteroidField.lua anpassen, mit 'Mineraliendichten-Parameter'.
57
58o Dokumentieren mit @brief?
59
60o replace ugly random stuff with math.rnd()
61o set collisionDamage? Just for static entities?
62
63HANDBUCH:
64o im Level-File includes/pickups.oxi importieren.
65o Bei der XML-Variante wird beim ersten Aufruf der Tick-Methode ein neuer Asteroid generiert,
66  damit die Groesse der Collision Shape korrekt initialisiert wird.
67
68FREMDANPASSUNGEN:
69Pickup-Zeug:
70o Pickup.h: Zugriffsänderung createSpawner
71o PickupSpawner.h: Zugriffsrechte setPickupTemplateName() und setMaxSpawnedItems()
72o PickupSpawner.h: In Tick() zwei Testbedingungen eingefuegt.
73o Pawn.h: Attribut acceptsPickups_ inklusive get/set.
74
75ERLEGT:
76o Rand() geht bis zu riesigen Nummern!
77o Pickupgenerierung: vgl. Fremdanpassungen.
78o Minimalbegrenzung fuer Masse vergessen.
79o Dynamische Definition -> putStuff-Methode, Werte noch nicht durchgesickert.
80o Error-Nachricht: Einfach Argumente leer lassen.
81o Pickups: setMaxSpawned funktioniert nicht -> Bastelloesung: Auf 2 statt eins setzen, erstes wird wohl direkt zerstoert.
82o setHealth: Wird mit Max verwurstelt, war 0.
83o Position nicht gesetzt -> alles im Ursprung, Kollision -> fliegt davon.
84o nimmt zuviel Schaden. -> wird mit maxHealth verwurstelt -> einfach auch setzen.
85
86o Groessenabhaengige Collison shape: Umweg ueber zweiten Konstruktor.
87o Absturz beim Asteroidengenerieren: Health war auf 0 gesetzt! Wurde nur bei der xml-Variante definiert.
88o Asteroiden fressen Pickups: Argument in Pawn, Test darauf in Tick() von PickupSpawner.
89
90NOTIZEN:
91o SUPER entspricht ueberladen, andere Argumente der Methode.
92o Warnungsverhinderung anderswo: (void)pickedUp; // To avoid compiler warning.
93
94Was ist das?         friend class Pickupable;
95
96
97
98*/
99
100
101#include "../../orxonox/worldentities/pawns/Pawn.h"
102#include "../../orxonox/worldentities/WorldEntity.h"
103
104#include "AsteroidMinable.h"
105
106#include <algorithm>
107
108#include "core/CoreIncludes.h"
109#include "core/GameMode.h"
110#include "core/XMLPort.h"
111#include "core/EventIncludes.h"
112#include "network/NetworkFunction.h"
113
114// #include "infos/PlayerInfo.h"
115// #include "controllers/Controller.h"
116// #include "gametypes/Gametype.h"
117// #include "graphics/ParticleSpawner.h"
118// #include "worldentities/ExplosionChunk.h"
119// #include "worldentities/ExplosionPart.h"
120
121// #include "core/object/ObjectListIterator.h"
122// #include "controllers/FormationController.h"
123
124#include "../pickup/items/HealthPickup.h"
125#include "../pickup/PickupSpawner.h"
126#include "../pickup/Pickup.h"
127//#include "../pickup/pickup ..... pickupable
128#include "../objects/collisionshapes/SphereCollisionShape.h"
129#include "../../orxonox/graphics/Model.h"
130
131
132
133
134
135
136namespace orxonox
137{
138    RegisterClass(AsteroidMinable);
139
140
141    // This constructor is for XML access only.
142    AsteroidMinable::AsteroidMinable(Context* context) : Pawn(context){
143
144        // Da auch noetig? Wegen set in XML-Code?
145        RegisterObject(AsteroidMinable);
146
147        this->context = context;
148        this->initialised = false;
149
150        //Noetig, damit nicht sofort zerstoert?
151        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
152
153        // Old from Pawn
154        this->registerVariables();
155
156        orxout() << "AsteroidMining:: Pseudo-Konstruktor passiert!" << endl;
157
158    }
159
160    // Call this one from other C-files. Takes arguments.
161    AsteroidMinable::AsteroidMinable(Context* c, float size, Vector3 position) : Pawn(c){
162
163        RegisterObject(AsteroidMinable);
164
165        // Old stuff from pawn
166        this->setRadarObjectColour(ColourValue(1.0f, 1.0f, 0.0f, 1.0f));
167        this->setRadarObjectShape(RadarViewable::Shape::Dot);
168        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
169
170        this->enableCollisionCallback();
171
172        // Default Values
173        this->generateSmaller = true; 
174        //this->setHealth(50);
175        this->context = c;
176        this->size = size; // customSize
177        this->health_ = 15*size;// capped at 200 in pawn or smth?
178        this->maxHealth_ = this->health_;
179        this->acceptsPickups_ = false;
180
181        this->setPosition(position);
182        //this->roll = rand()*5; //etwas Drehung. richtige Variable
183
184        // // Fliegt davon, irgendwieso. Dies scheint auch nicht zu nuetzen.
185        // this->setVelocity(Vector3(0,0,0));
186
187
188
189        // Add Model    //<Model position="0,-40,40" yaw="90" pitch="-90" roll="0" scale="4" mesh="ast6.mesh" />
190        Model* hull = new Model(this->context);
191        // random one of the 6 shapes
192        char meshThingy[] = "";
193        sprintf(meshThingy, "ast%.0f.mesh", (round((5*(double)rand()/(double)RAND_MAX))+1)); //    sprintf(str, "Value of Pi = %f", M_PI);
194        hull->setMeshSource(meshThingy);
195        hull->setScale(this->size);
196        this->attach(hull);
197
198        // Collision shape
199        SphereCollisionShape* cs = new SphereCollisionShape(this->context);
200        cs->setRadius((this->size)*2); //OFFEN: Feinabstimmung der Radien. 2.5 in AsteroidField.lua
201        this->attachCollisionShape(cs); 
202
203        // Old from Pawn
204        this->registerVariables();
205
206        this->initialised=true; 
207
208        orxout() << "AsteroidMining:: Initialisierung Zweitkonstruktor abgeschlosssssen." << endl;
209
210    }
211
212    AsteroidMinable::~AsteroidMinable(){
213
214    }
215
216    void AsteroidMinable::putStuff(){
217
218        // Just create a new asteroid to avoid Collision shape scale problems etc.
219        AsteroidMinable* reborn = new AsteroidMinable(this->context, this->size, this->getPosition());
220        reborn->toggleShattering(true); // mainly here to avoid 'unused' warning.
221        this->~AsteroidMinable(); // seems dangerous. Necessary for efficiency?
222
223    }
224
225    void AsteroidMinable::XMLPort(Element& xmlelement, XMLPort::Mode mode)
226    {
227        SUPER(AsteroidMinable, XMLPort, xmlelement, mode);
228        //        XMLPortParam(PickupSpawner, "pickup", setPickupTemplateName, getPickupTemplateName, xmlelement, mode);
229        XMLPortParam(AsteroidMinable, "size", setSize, getSize, xmlelement, mode);
230
231    }
232
233    void AsteroidMinable::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
234    {
235        SUPER(AsteroidMinable, XMLEventPort, xmlelement, mode);
236
237        XMLPortEventState(AsteroidMinable, BaseObject, "vulnerability", setVulnerable, xmlelement, mode);
238    }
239
240    void AsteroidMinable::registerVariables()
241    {
242        // registerVariable(this->bAlive_,            VariableDirection::ToClient);
243        // registerVariable(this->bVulnerable_,       VariableDirection::ToClient);
244        // registerVariable(this->health_,            VariableDirection::ToClient);
245        // registerVariable(this->maxHealth_,         VariableDirection::ToClient);
246
247        registerVariable(this->size, VariableDirection::ToClient);
248        registerVariable(this->generateSmaller, VariableDirection::ToClient);
249
250        registerVariable(this->initialised, VariableDirection::ToClient);
251        //registerVariable(this->context, VariableDirection::ToClient); // can't link that since it's a context
252
253
254            //         float size;
255            // bool generateSmaller;
256            // bool initialised;
257
258            // Context* context;
259    }
260
261    void AsteroidMinable::tick(float dt)
262    {
263        if(!(this->initialised)){this->putStuff();}
264
265        if(this->health_ <=0){this->death();}
266
267        // if(this->initialised){
268        //     // this->setVelocity(Vector3(0,0,0));  // Funktioniert, scheint aber unsinnig.
269        //     orxout() << "Flying at speed: " << this->getVelocity() << endl;
270        // }
271
272    }
273
274    void AsteroidMinable::setSize(float s){
275        this->size = s;
276    }
277
278    float AsteroidMinable::getSize(){
279        return this->size;
280    }
281
282    void AsteroidMinable::toggleShattering(bool b){
283        this->generateSmaller = b;
284    }
285
286
287    void AsteroidMinable::death() //ueberschreiben
288    {
289
290        // orxout() << "AsteroidMinable::Death() aufgerufen." << endl;
291
292        // OFFEN: Sauber kapputten
293        // just copied other stuff:
294        // this->setHealth(1);
295        this->bAlive_ = false;
296        this->destroyLater();
297        this->setDestroyWhenPlayerLeft(false);
298        // pawn -> addExplosionPart
299        // this->goWithStyle();
300
301
302        // Stuff that can be harvested.
303        PickupSpawner* thingy = new PickupSpawner(this->context);
304        // OFFEN: more precise size relation in custom resource pickup.
305        char tname[] = ""; // can-t overwrite strings easily in C (strcat etc.)
306        if(this->size <= 5){
307            strcat(tname, "smallmunitionpickup");
308        }else if(this->size <= 20){
309            strcat(tname, "mediummunitionpickup");
310        }else{
311            strcat(tname, "hugemunitionpickup");
312        }
313        thingy->setPickupTemplateName(tname);
314        thingy->setPosition(this->getPosition());
315        thingy->setMaxSpawnedItems(1); // Would be default anyways
316        thingy->setRespawnTime(0.2f);
317
318        // orxout() << "AsteroidMining::Death(): Passed Pickup stuff!" << endl;
319
320        // Smaller Parts = 'Children'
321        if(this->generateSmaller){
322            this->spawnChildren();
323        }
324
325        // orxout() << "Wieder retour in death() geschafft. " << endl;
326
327    }
328
329
330void AsteroidMinable::spawnChildren(){
331   
332    if (this->size <=1){return;} // Absicherung trivialer Fall
333
334    // Spawn smaller Children
335    int massRem = this->size-1; //some mass is lost
336    int num = round((massRem-1)*(double)rand() / (double)RAND_MAX)+1; // random number of children, at least one // Tweak towards bigger junks?
337    if(num > 10){num = 10;} // no max function in C!
338
339    // num = 1; // zum Testen mal nur einen generieren.
340
341    // // TODO: Check this draft for edge cases etc.
342    // // 'Triangular', discrete probability density with max at massRem/num
343    // // Max at a, value 1, subintervals a+b = c
344    // int c = massRem-num;
345    // float probDensity = [c]
346    // int a = round(massRem/num);
347    // int b = c-a;
348    // for(int z = 0; z<=a; z++){probDensity[z] = m*z/a; } // rising part
349    // for(z = a+1; z<c; z++){probDensity[z] = m - m*(z-a)/b;} // falling part
350
351    // double rand = (double)rand() / (double)RAND_MAX; // between 0 and 1
352    // double probSum = 0;
353    // int result = 0;
354    // while(rand>probSum){
355    //     probSum = probSum+probDensity[result];
356    //     result++:
357    // }
358
359
360    massRem = massRem-num;   
361
362    int extra = 0;
363
364    //orxout() << "Number of Children: " << num << endl;
365
366
367    for(int fisch=num; fisch>=1; --fisch){
368        // to distribute remaining mass
369
370        //orxout() << "AsteroidMining::spawnChildren(): Fisch-Variable: " << fisch << endl;
371
372        if(fisch==1){ 
373            extra = massRem;
374        }else{
375            extra = round(massRem*(double)rand() / (double)RAND_MAX);
376            massRem = massRem-extra;
377
378        }
379
380        //orxout() << "Mass chosen: " << extra+1 << endl;
381
382        //orxout() << "AsteroidMining::spawnChildren(): Inside for-loop." << endl;
383
384        //Spawn this child  Game crashes!
385        //AsteroidMinable* child = new AsteroidMinable(this->context);
386        int newMass = extra+1; 
387        AsteroidMinable* child = new AsteroidMinable(this->context, newMass, this->getPosition() + Vector3(fisch*newMass*2.5, 0, 0));
388        // if(!(child == nullptr)){//Errorgebastel
389
390        // Position zu spaet gesetzt? Tick nicht atomar -> falsche Groesse evtl?
391
392        // child->setSize(extra + 1);
393               
394        //     //OFFEN:Kollision der Kinder verhindern
395        //     //Relativ zu Elternteil automatisch?
396        //     //Typ position:rand()*Vektoriwas?
397        //     //pawn->getWorldPosition() + Vector3(30,0,-30);
398        // child->setPosition(this->getPosition() + Vector3(num*5, 0, 0));
399        // //child->setPosition(Vector3(0,0,0));
400
401        if(child == nullptr){
402            orxout(internal_error, context::pickups) << "Weird, can't create new AsteroidMinable." << endl;
403        }
404
405
406
407        //orxout() << "Done: Creating new Asteroid" << endl;
408
409        // }
410
411
412                //         Pawn* pawn = this->carrierToPawnHelper();
413                // if(pawn == nullptr) // If the PickupCarrier is no Pawn, then this pickup is useless and therefore is destroyed.
414                //     this->Pickupable::destroy();
415
416                // //Attach to pawn
417                // Drone* drone = new Drone(pawn->getContext()); // this is neccessary because the projectiles fired need a valid creator for the particlespawner (when colliding against something)
418                // drone->addTemplate(this->getDroneTemplate());
419
420
421    }
422    // orxout() << "Leaving spawnChildren() method. " << endl;
423}
424
425
426    void AsteroidMinable::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
427
428        orxout() << "AsteroidMining::Hit(Variante 1) Dings aufgerufen. " << endl;
429
430        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
431        // Wird staending aufgerufen -> Rechenleistung?
432        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
433        this->damage(damage, healthdamage, shielddamage, originator, cs);
434        this->setVelocity(this->getVelocity() + force);
435
436
437
438        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
439        // {
440        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
441        //     this->setVelocity(this->getVelocity() + force);
442        // }
443    }
444
445    void AsteroidMinable::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
446
447        //orxout() << "AsteroidMining::Hit(Variante 2) Dings aufgerufen. " << endl;
448        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
449        // Wird staending aufgerufen -> Rechenleistung?
450        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
451
452        //orxout() << "Schaden. HP: " << this->health_ << " Dmg: " << damage << " hDmg: " << healthdamage << " sDmg: " << shielddamage << endl;
453
454        this->damage(damage, healthdamage, shielddamage, originator, cs);
455
456
457
458
459        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
460        // {
461        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
462
463        //     //if ( this->getController() )
464        //     //    this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
465        // }
466    }
467
468
469
470
471
472
473//Pawn:
474    // void Pawn::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
475    // {
476    //     if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
477    //     {
478    //         this->damage(damage, healthdamage, shielddamage, originator, cs);
479    //         this->setVelocity(this->getVelocity() + force);
480    //     }
481    // }
482
483    // void Pawn::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage)
484    // {
485    //     if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator) && (!this->getController() || !this->getController()->getGodMode()) )
486    //     {
487    //         this->damage(damage, healthdamage, shielddamage, originator, cs);
488
489    //         if ( this->getController() )
490    //             this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
491    //     }
492    // }
493
494
495
496
497            // /**
498            // @brief
499            //     Virtual function that gets called when this object collides with another.
500            // @param otherObject
501            //     The object this one has collided into.
502            // @param ownCollisionShape
503            //     The collision shape of the other object
504            // @param contactPoint
505            //     Contact point provided by Bullet. Holds more information and can me modified. See return value.
506            // @return
507            //     Returning false means that no modification to the contactPoint has been made. Return true otherwise!
508            // @note
509            //     Condition is that enableCollisionCallback() was called.
510            // */
511            // virtual inline bool collidesAgainst(WorldEntity* otherObject, const btCollisionShape* ownCollisionShape, btManifoldPoint& contactPoint)
512            //     { return false; } /* With false, Bullet assumes no modification to the collision objects. */
513
514            // //! Enables the collidesAgainst(.) function. The object doesn't respond to collision otherwise!
515            // inline void enableCollisionCallback()
516            //     { this->bCollisionCallbackActive_ = true; this->collisionCallbackActivityChanged(); }
517
518
519
520            // //! Disables the collidesAgainst(.) function. @see enableCollisionCallback()
521            // inline void disableCollisionCallback()
522            //     { this->bCollisionCallbackActive_ = false; this->collisionCallbackActivityChanged(); }
523
524
525            // //! Tells whether there could be a collision callback via collidesAgainst(.)
526            // inline bool isCollisionCallbackActive() const
527            //     { return this->bCollisionCallbackActive_; }
528
529            // //! Enables or disables collision response (default is of course on)
530            // inline void setCollisionResponse(bool value)
531            //     { this->bCollisionResponseActive_ = value; this->collisionResponseActivityChanged(); }
532
533
534            // //! Tells whether there could be a collision response
535            // inline bool hasCollisionResponse()
536            //     { return this->bCollisionResponseActive_; }
537
538
539}
540
541
542
543
544
545/*
546    void DronePickup::changedUsed(void)
547    {
548        SUPER(DronePickup, changedUsed);
549
550        // If the pickup has transited to used.
551        if(this->isUsed())
552        {
553
554                Pawn* pawn = this->carrierToPawnHelper();
555                if(pawn == nullptr) // If the PickupCarrier is no Pawn, then this pickup is useless and therefore is destroyed.
556                    this->Pickupable::destroy();
557
558                //Attach to pawn
559                Drone* drone = new Drone(pawn->getContext()); // this is neccessary because the projectiles fired need a valid creator for the particlespawner (when colliding against something)
560                drone->addTemplate(this->getDroneTemplate());
561
562                Controller* controller = drone->getController();
563                DroneController* droneController = orxonox_cast<DroneController*>(controller);
564                if(droneController != nullptr)
565                {
566                    droneController->setOwner(pawn);
567                }
568
569                Vector3 spawnPosition = pawn->getWorldPosition() + Vector3(30,0,-30);
570                drone->setPosition(spawnPosition);
571
572                // The pickup has been used up.
573                this->setUsed(false);
574        }
575        else
576        {
577            // If either the pickup can only be used once or it is continuous and used up, it is destroyed upon setting it to unused.
578            if(this->isOnce() || (this->isContinuous() ))
579            {
580                this->Pickupable::destroy();
581            }
582        }
583    }
584*/
Note: See TracBrowser for help on using the repository browser.