Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

Major breakthrough: Variable Collision shape works, error in spawnChildren() found (health…). Smaller problems remain (Weird initial velocity, correct health setting).

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