Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 11665 was 11664, checked in by remartin, 7 years ago

SpicedAsteroidBelt erstellt, kosmetische Veränderungen. Offener Punkt um velocity, ansonsten fehlt nur noch das dokumentieren.

File size: 18.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 *      Simon Miescher
26 *
27 */
28
29/*
30
31    @file AsteroidMinable.cc
32
33*
34*
35* An asteroid which can be destroyed. Some smaller asteroids are created and a pickup
36* spawns.
37*
38*
39*
40
41*/
42
43/*
44Veraenderungstagebuch
45++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
46
47
48KNACKPUNKTE:
49o Super-XML-Argumente werden nicht richtig geparst (Velocity, Pitch, Yaw etc. )
50
51
52OFFEN:
53
54o Add custom pickup 'resources'. Weird template stuff -> Problems setting 'size' and other properties? setNumber of Resources.
55--> PickupTemplateName_ in PickupSpawner ist ein string. Wird via getBaseClassIdentifier ausgelesen, daraus wird ein Pickupable fabriziert.
56--> MunitionPickup erbt von Pickup erbt von collectiblePickup erbt von Pickupable
57----> im MineralsPickup die isPickedUp()-Methode überschreiben?
58--> data_extern/images/effects: PNG's für die Pickups und GUI-Dinger.
59--> https://www.orxonox.net/jenkins/view/Management/job/orxonox_doxygen_trunk/javadoc/group___pickup.html
60
61o Anfangsgeschwindigkeit fuers Asteroidenfeld
62o Density doesn't add up to 1...
63o set collisionDamage? Just for static entities?
64
65o Dokumentieren mit @brief?
66o unregister -empty- asteroids from radar. (or turn them green or whatever)
67o Add sound effect (crunching etc. ) (No sound in space...)
68o Explosion parts
69
70HANDBUCH:
71o im Level-File includes/pickups.oxi importieren.
72o Bei der XML-Variante wird beim ersten Aufruf der Tick-Methode ein neuer Asteroid generiert,
73  damit die Groesse der Collision Shape korrekt initialisiert wird.
74
75FREMDANPASSUNGEN:
76Pickup-Zeug:
77o Pickup.h: Zugriffsänderung createSpawner
78o PickupSpawner.h: Zugriffsrechte setPickupTemplateName() und setMaxSpawnedItems()
79o PickupSpawner.h: In Tick() zwei Testbedingungen eingefuegt.
80o Pawn.h: Attribut acceptsPickups_ inklusive get/set.
81
82ERLEGTE FEHLER:
83o Rand() geht bis zu riesigen Nummern!
84o Pickupgenerierung: vgl. Fremdanpassungen.
85o Minimalbegrenzung fuer Masse vergessen.
86o Dynamische Definition -> putStuff-Methode, Werte noch nicht durchgesickert.
87o Error-Nachricht: Einfach Argumente leer lassen.
88o Pickups: setMaxSpawned funktioniert nicht -> Bastelloesung: Auf 2 statt eins setzen, erstes wird wohl direkt zerstoert.
89o setHealth: Wird mit Max verwurstelt, war 0.
90o Position nicht gesetzt -> alles im Ursprung, Kollision -> fliegt davon.
91o nimmt zuviel Schaden. -> wird mit maxHealth verwurstelt -> einfach auch setzen.
92
93o Groessenabhaengige Collison shape: Umweg ueber zweiten Konstruktor.
94o Absturz beim Asteroidengenerieren: Health war auf 0 gesetzt! Wurde nur bei der xml-Variante definiert.
95o Asteroiden fressen Pickups: Argument in Pawn, Test darauf in Tick() von PickupSpawner.
96o Man kann keine Arrays der Groesse 0 initialisieren, aber auch nicht per IF 2x definieren.
97o i++ einfach ganz verhindern, ++i stattdessen.
98o Discusting mixup with array length, accessing element a[len]...
99o unitialised mass value -> obese asteroid, physics bug.
100
101
102NOTIZEN:
103o SUPER entspricht ueberladen, andere Argumente der Methode.
104o Warnungsverhinderung anderswo: (void)pickedUp; // To avoid compiler warning.
105
106Was ist das?         friend class Pickupable;
107
108
109
110*/
111
112
113#include "../../orxonox/worldentities/pawns/Pawn.h"
114#include "../../orxonox/worldentities/WorldEntity.h"
115
116#include "AsteroidMinable.h"
117
118#include <algorithm>
119
120#include "core/CoreIncludes.h"
121#include "core/GameMode.h"
122#include "core/XMLPort.h"
123#include "core/EventIncludes.h"
124#include "network/NetworkFunction.h"
125#include "util/Math.h"
126
127#include "../pickup/PickupSpawner.h"
128#include "../pickup/Pickup.h"
129
130#include "../objects/collisionshapes/SphereCollisionShape.h"
131#include "../../orxonox/graphics/Model.h"
132
133
134namespace orxonox{
135
136    RegisterClass(AsteroidMinable);
137
138    // @brief Standard constructor
139    AsteroidMinable::AsteroidMinable(Context* context) : Pawn(context){
140
141        RegisterObject(AsteroidMinable);
142        this->context = context;
143
144        // Default Values:
145        this->size = 10; 
146        this->dropStuff = true; 
147        this->generateSmaller = true; 
148        this->health_ = 15*size; 
149        this->maxHealth_ = this->health_;
150        this->acceptsPickups_ = false; 
151
152        //Noetig, damit nicht sofort zerstoert?
153        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
154        this->enableCollisionCallback();
155
156
157        // Old from Pawn
158        this->registerVariables();
159
160        this->initialised = false;
161
162    }
163
164    // @brief Use this constructor with care. Mainly used internally, arguments are passed directly.
165    AsteroidMinable::AsteroidMinable(Context* c, float size, Vector3 position, Vector3 v, bool dropStuff) : Pawn(c){
166
167        RegisterObject(AsteroidMinable);
168
169        // The radar is able to detect whether an asteroid contains resources....
170        if(dropStuff){
171            this->setRadarObjectColour(ColourValue(1.0f, 1.0f, 0.0f, 1.0f));
172            this->setRadarObjectShape(RadarViewable::Shape::Dot);
173        }else{
174            // Somehow remove from radar?
175        }
176
177        this->context = c;
178        this->size = size;
179        this->health_ = 15*size; 
180        this->maxHealth_ = this->health_;
181        this->acceptsPickups_ = false; 
182        this->generateSmaller = true; 
183        this->dropStuff = dropStuff; 
184
185        this->setPosition(position);
186        this->setVelocity(v); 
187        //this->roll = rand()*5; //etwas Drehung. Richtige Variable?
188
189        this->setCollisionType(WorldEntity::CollisionType::Dynamic);
190        this->enableCollisionCallback();
191
192
193        // Add Model, random one of the 6 shapes
194        Model* hull = new Model(this->context);
195        char meshThingy[] = "";
196        sprintf(meshThingy, "ast%.0f.mesh", round(5*rnd())+1); 
197        hull->setMeshSource(meshThingy);
198        hull->setScale(this->size);
199        this->attach(hull);
200
201        // Collision shape
202        SphereCollisionShape* cs = new SphereCollisionShape(this->context);
203        cs->setRadius((this->size)*2); //OFFEN: Feinabstimmung der Radien.
204        this->attachCollisionShape(cs); 
205
206        this->registerVariables();
207
208        this->initialised=true; 
209
210    }
211
212    AsteroidMinable::~AsteroidMinable(){
213
214    }
215
216    // @brief Helper method. Create a new asteroid to have an appropriate size for the collision shape etc.
217    void AsteroidMinable::putStuff(){
218
219        // Just create a new asteroid to avoid Collision shape scale problems etc.
220        AsteroidMinable* reborn = new AsteroidMinable(this->context, this->size, this->getPosition(), this->getVelocity(), this->dropStuff);
221        (void)reborn; // avoid compiler warning
222        this->bAlive_ = false;
223        this->destroyLater();
224
225    }
226
227    void AsteroidMinable::XMLPort(Element& xmlelement, XMLPort::Mode mode){
228
229        SUPER(AsteroidMinable, XMLPort, xmlelement, mode); 
230
231        XMLPortParam(AsteroidMinable, "size", setSize, getSize, xmlelement, mode);
232        XMLPortParam(AsteroidMinable, "generateSmaller", toggleShattering, doesShatter, xmlelement, mode);
233        XMLPortParam(AsteroidMinable, "dropStuff", toggleDropStuff, doesDropStuff, xmlelement, mode); 
234
235    }
236
237    void AsteroidMinable::XMLEventPort(Element& xmlelement, XMLPort::Mode mode){
238
239        SUPER(AsteroidMinable, XMLEventPort, xmlelement, mode);
240
241    }
242
243    void AsteroidMinable::registerVariables(){
244
245        registerVariable(this->size, VariableDirection::ToClient);
246        registerVariable(this->generateSmaller, VariableDirection::ToClient);
247        registerVariable(this->dropStuff, VariableDirection::ToClient); 
248        registerVariable(this->initialised, VariableDirection::ToClient);
249
250    }
251
252    void AsteroidMinable::tick(float dt){
253
254        if(!(this->initialised)){this->putStuff();} 
255
256        if(this->health_ <=0){this->death();}
257
258    }
259
260    void AsteroidMinable::death(){ // ueberschreibt das Zeug in Pawn
261
262        // just copied that from somewhere else.
263        this->bAlive_ = false;
264        this->destroyLater();
265        this->setDestroyWhenPlayerLeft(false);
266        // pawn -> addExplosionPart
267        // this->goWithStyle();
268
269
270        // Pickups which can be harvested.
271        if(dropStuff){
272            PickupSpawner* thingy = new PickupSpawner(this->context);
273            // OFFEN: more precise size relation in custom resource pickup.
274            char tname[] = ""; // can-t overwrite strings easily in C (strcat etc.)
275            if(this->size <= 5){
276                strcat(tname, "smallmunitionpickup");
277            }else if(this->size <= 20){
278                strcat(tname, "mediummunitionpickup");
279            }else{
280                strcat(tname, "hugemunitionpickup");
281            }
282            thingy->setPickupTemplateName(tname);
283            thingy->setPosition(this->getPosition());
284            thingy->setMaxSpawnedItems(1); // Would be default anyways
285            thingy->setRespawnTime(0.2f);
286        }
287
288        // Smaller Parts = 'Children'
289        if(this->generateSmaller){this->spawnChildren();}
290
291    }
292
293
294void AsteroidMinable::spawnChildren(){// Spawn smaller Children
295
296    if (this->size <=1){return;} // Absicherung trivialer Fall
297
298    int massRem = this->size-1; //some mass is lost
299    int num = round(rnd()*(massRem-1)) + 1; // random number of children, at least one
300    if(num > 10){num = 10;} // no max function in C!
301    int masses[num]; // Masses of the asteroids, at least one.
302
303    // orxout() << "SpawnChildren(): Passed basic stuff. num = " << num << "; massRem(total) = "<< massRem << endl;
304
305    massRem = massRem-num; // mass is at least one, add again below.
306
307    // Randomnised spawning points for the new asteroids
308    float phi[num]; 
309    float theta[num]; 
310
311    // Discusting C stuff -> use that to initialise dynamic array values to 0.
312    for(int twat = 0; twat<num; ++twat){masses[twat] = 0; phi[twat] = 0.0; theta[twat] = 0.0;}
313
314    float piG = 3.1415927410125732421875; //pi; // Math.pi ist statisch oder so.
315    float d_p = 2*piG/num;
316    float d_t = piG/num;
317    float p = d_p/2.0;
318    float t = d_t/2.0;
319    // float phiOffset = rnd()*2*pi; // Added everywhere to become independent of the coordinate system?
320    // float thetaOffset = rnd()*pi;
321    float rScaling; // scale radius to prevent asteroids from touching. (distance=AsteroidRadius/tan(sector/2))
322
323    if(num == 1 ){
324        rScaling = 1; // avoid tan(90). Unused.
325    }else{
326
327        rScaling = tan(t); 
328
329        int pos; // insert at random position (linear probing) in array, to get some randomness. 
330        for(int it = 0; it<num; ++it){
331
332            pos = mod((int)(rnd()*num),num); 
333            while(phi[pos] != 0.0){// find empty spot in array
334                pos = (int)mod(++pos, num);
335            }
336            phi[pos] = p + it*d_p;// set angle there
337
338            pos = mod((int)(rnd()*num),num);
339            while(theta[pos] != 0.0){
340                pos = (int)mod(++pos, num);
341            }
342            theta[pos] = t + it*d_t;
343        }
344    }
345
346    //orxout() << "SpawnChildren(): Phi: "; printArrayString(phi);
347    //orxout() << "SpawnChildren(): Theta: "; printArrayString(theta);
348    //orxout() << "SpawnChildren(): Passed angle stuff. " << endl;
349
350    // 'Triangular', discrete probability "density" with max at the expected value massRem/num at a. a+b = c
351    if(massRem>0){ // Required to avoid array of size 0 or access problems
352        int c = massRem;
353        float probDensity[c];
354
355        int a = round(massRem/num);
356        int b = c-a;
357       
358        int z = 0;
359        float dProbA = 1.0/(a*a + 3.0*a + 2.0); // one 'probability unit' for discrete ramp function. Gauss stuff.
360        for(z = 0; z<=a; ++z){probDensity[z] = (z+1)*dProbA; } // rising part
361
362        float dProbB = 1.0/(b*b +3.0*b + 2.0);
363        for(z = 0; z<b; ++z){probDensity[c-z] = (z+1)*dProbB;} // falling part
364   
365        // // Just for testing:
366        // float sum = 0.0;
367        // for(int globi = 0; globi<c; ++globi){
368        //     orxout() << "pDensity at [" << globi << "] is: " << probDensity[globi] << endl;
369        //     sum = sum+ probDensity[globi];
370        // }
371        // orxout() << "Sum of densities should b 1, it is: " << sum << endl;
372
373        // Distributing the mass to individual asteroids
374        int result;
375        float rVal;// between 0 and 1
376        float probSum;
377        for(int trav = 0; trav<num; ++trav){
378            result = 0;// reset
379            rVal = rnd();// between 0 and 1
380            probSum = probDensity[0]; 
381
382            while(rVal>probSum && result<massRem){// Not yet found && there-s smth left to distribute (Incrementing once inside!)
383                if(result<(massRem-2)){probSum = probSum + probDensity[result+1];} // avoid logical/acess error
384                ++result;
385            }
386
387            massRem = massRem-result;
388            masses[trav] = 1 +result; // Fragments have mass of at least one.
389        }
390    }else{
391        for(int schnaegg = 0; schnaegg<num; ++schnaegg){masses[schnaegg] = 1;}
392    }
393
394    // orxout() << "SpawnChildren(): Masses: "; printArrayString(masses);
395    // orxout() << "SpawnChildren(): Passed mass stuff. " << endl;
396
397    // Creating the 'chlidren':
398    for(int fisch = 0; fisch<num; ++fisch){
399
400        Vector3* pos = new Vector3(0,0,0); // Position offset
401        if(num > 1){// not required if there-s just one child
402            float r = masses[fisch]/rScaling;
403            pos = new Vector3(r*sin(theta[fisch])*cos(phi[fisch]), r*sin(theta[fisch])*sin(phi[fisch]), r*cos(theta[fisch])); // convert spheric coordinates to vector
404        }
405       
406        AsteroidMinable* child = new AsteroidMinable(this->context, masses[fisch], this->getPosition() + *pos, this->getVelocity(), this->dropStuff);
407
408        if(child == nullptr){
409            orxout(internal_error, context::pickups) << "Weird, can't create new AsteroidMinable." << endl;
410        }
411
412    }
413    // orxout() << "Leaving spawnChildren() method. " << endl;
414}
415
416
417    void AsteroidMinable::hit(Pawn* originator, const Vector3& force, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
418
419        orxout() << "AsteroidMining::Hit(Variante 1) Dings aufgerufen. " << endl;
420
421        // Kollision mit anderem Asteroid oder Pickup verhindern. In diesem Fall einfach nichts tun.
422        // Wird staending aufgerufen -> Rechenleistung?
423        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
424        this->damage(damage, healthdamage, shielddamage, originator, cs);
425        this->setVelocity(this->getVelocity() + force);
426
427
428
429        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
430        // {
431        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
432        //     this->setVelocity(this->getVelocity() + force);
433        // }
434    }
435
436    void AsteroidMinable::hit(Pawn* originator, btManifoldPoint& contactpoint, const btCollisionShape* cs, float damage, float healthdamage, float shielddamage){
437
438        //orxout() << "AsteroidMining::Hit(Variante 2) Dings aufgerufen. " << endl;
439        // Kollision mit anderem Asteroid oder Pickup (OFFEN: evtl. Spawner oder irgendwas?) verhindern. In diesem Fall einfach nichts tun.
440        // Wird staending aufgerufen -> Rechenleistung?
441        if(orxonox_cast<AsteroidMinable*>(originator) || orxonox_cast<Pickup*>(originator)){return;}
442
443        //orxout() << "Schaden. HP: " << this->health_ << " Dmg: " << damage << " hDmg: " << healthdamage << " sDmg: " << shielddamage << endl;
444
445        this->damage(damage, healthdamage, shielddamage, originator, cs);
446
447
448
449
450        // if (this->getGametype() && this->getGametype()->allowPawnHit(this, originator))// && (!this->getController() || !this->getController()->getGodMode()) )
451        // {
452        //     this->damage(damage, healthdamage, shielddamage, originator, cs);
453
454        //     //if ( this->getController() )
455        //     //    this->getController()->hit(originator, contactpoint, damage); // changed to damage, why shielddamage?
456        // }
457    }
458
459    // @brief Just for testing. Don-t work anyways.
460    void AsteroidMinable::printArrayString(float thingy[]){ // Don-t work!
461
462        orxout() << "[" ; //<< endl; 
463        char frag[] = "";
464        int len = (int)(sizeof(thingy)/sizeof(thingy[0]));
465        for(int m = 0; m< (len-2); ++m){
466            sprintf(frag, "%.5f, ", thingy[m]);
467            orxout() << frag << endl;//std::flush;
468        }
469        sprintf(frag, "%.5f]", thingy[len-1]);
470        orxout() << frag << endl; // Just print it here! No ugly passing.
471    }
472
473    // @brief Just for testing. Don-t work anyways.
474    void AsteroidMinable::printArrayString(int thingy[]){
475
476        orxout() << "[" ; //<< endl;
477        char frag[] = "";
478        int len = (int)(sizeof(thingy)/sizeof(thingy[0]));
479        for(int m = 0; m< (len-2); ++m){
480            sprintf(frag, "%.0i, ", thingy[m]);
481            orxout() << frag << endl;//std::flush;
482            printf("TEst");
483        }
484
485        sprintf(frag, "%.0i]", thingy[len-1]); // last element
486        orxout() << frag << endl; // Just print it here! No ugly passing.
487    }
488
489    // void AsteroidMinable::printArrayString(int thingy[]){
490    //     char res[] = "[";
491    //     //strcat(res, "[");
492    //     char frag[] = "";
493
494    //     int len = (int)(sizeof(thingy)/sizeof(thingy[0]));
495    //     for(int m = 0; m< (len-1); ++m){
496    //         sprintf(frag, "%.0i, ", thingy[m]);
497    //         strcat(res, frag);
498    //     }
499    //     sprintf(frag, "%.0i]", thingy[len]);
500    //     strcat(res, frag); // last element
501
502    //     orxout() << res << endl; // Just print it here! No ugly passing.
503
504    //     // static char result[(sizeof(res)/sizeof("")] = res; // define as static, would get deleted otherwise.
505    //     // char *result = malloc(sizeof(res)/sizeof("") + 1);
506    //     // *result = res;
507    //     // return result;
508    // }
509
510}
Note: See TracBrowser for help on using the repository browser.