Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/radarDreiD/src/libraries/util/Math.cc @ 9877

Last change on this file since 9877 was 9877, checked in by wroennin, 10 years ago

Math: New function to determine the ZOrder of the radarobjects; HUDTemplates: cleenup

  • Property svn:eol-style set to native
File size: 21.6 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 *      Wolfgang Roenninger
26 *
27 */
28
29/**
30    @file
31    @brief Implementation of several math-functions.
32*/
33
34#include "Math.h"
35
36#include <OgrePlane.h>
37
38#include "MathConvert.h"
39#include "SubString.h"
40
41namespace orxonox
42{
43#if OGRE_VERSION < 0x010603
44    /**
45        @brief Function for writing a Radian to a stream.
46    */
47    std::ostream& operator<<(std::ostream& out, const orxonox::Radian& radian)
48    {
49        out << radian.valueRadians();
50        return out;
51    }
52
53    /**
54        @brief Function for writing a Degree to a stream.
55    */
56    std::ostream& operator<<(std::ostream& out, const orxonox::Degree& degree)
57    {
58        out << degree.valueDegrees();
59        return out;
60    }
61#endif
62
63    /**
64        @brief Function for reading a Radian from a stream.
65    */
66    std::istream& operator>>(std::istream& in, orxonox::Radian& radian)
67    {
68        float temp;
69        in >> temp;
70        radian = temp;
71        return in;
72    }
73
74    /**
75        @brief Function for reading a Degree from a stream.
76    */
77    std::istream& operator>>(std::istream& in, orxonox::Degree& degree)
78    {
79        float temp;
80        in >> temp;
81        degree = temp;
82        return in;
83    }
84
85
86    /**
87        @brief Gets the angle between my viewing direction and the direction to the position of the other object.
88        @param myposition My position
89        @param mydirection My viewing direction
90        @param otherposition The position of the other object
91        @return The angle in radian
92
93        Examples:
94         - If the other object is exactly in front of me, the function returns 0.
95         - If the other object is exactly behind me, the function returns pi.
96         - If the other object is exactly right/left to me (or above/below), the function returns pi/2.
97    */
98    float getAngle(const orxonox::Vector3& myposition, const orxonox::Vector3& mydirection, const orxonox::Vector3& otherposition)
99    {
100        orxonox::Vector3 distance = otherposition - myposition;
101        float distancelength = distance.length();
102        if (distancelength == 0)
103            return 0;
104        else
105            return acos(clamp<float>(mydirection.dotProduct(distance) / distancelength, -1, 1));
106    }
107
108    /**
109        @brief Gets the 2D viewing direction (up/down, left/right) to the position of the other object.
110        @param myposition My position
111        @param mydirection My viewing direction
112        @param myorthonormal My orthonormalvector (pointing upwards through my head)
113        @param otherposition The position of the other object
114        @return The viewing direction
115
116        Examples:
117         - If the other object is exactly in front of me, the function returns <tt>Vector2(0, 0)</tt>.
118         - If the other object is exactly at my left, the function returns <tt>Vector2(-1, 0)</tt>.
119         - If the other object is exactly at my right, the function returns <tt>Vector2(1, 0)</tt>.
120         - If the other object is only a bit at my right, the function still returns <tt>Vector2(1, 0)</tt>.
121         - If the other object is exactly above me, the function returns <tt>Vector2(0, 1)</tt>.
122    */
123    orxonox::Vector2 get2DViewdirection(const orxonox::Vector3& myposition, const orxonox::Vector3& mydirection, const orxonox::Vector3& myorthonormal, const orxonox::Vector3& otherposition)
124    {
125        orxonox::Vector3 distance = otherposition - myposition;
126
127        // project difference vector on our plane
128        orxonox::Vector3 projection = Ogre::Plane(mydirection, myposition).projectVector(distance);
129
130        float projectionlength = projection.length();
131        if (projectionlength == 0)
132        {
133            if (myposition.dotProduct(otherposition) >= 0)
134                return orxonox::Vector2(0, 0);
135            else
136                return orxonox::Vector2(0, 1);
137        }
138
139        float cos_value = clamp<float>(myorthonormal.dotProduct(projection) / projectionlength, -1, 1);
140        float sin_value = sqrt( 1 - cos_value*cos_value );
141
142        if ((mydirection.crossProduct(myorthonormal)).dotProduct(distance) > 0)
143            return orxonox::Vector2( sin_value, cos_value );
144        else
145            return orxonox::Vector2( -sin_value, cos_value );
146    }
147
148    /**
149        @brief Gets the 2D viewing direction (up/down, left/right) to the position of the other object, multiplied with the viewing distance to the object (0� = 0, 180� = 1).
150        @param myposition My position
151        @param mydirection My viewing direction
152        @param myorthonormal My orthonormalvector (pointing upwards through my head)
153        @param otherposition The position of the other object
154        @return The viewing direction
155
156        Examples:
157         - If the other object is exactly in front of me, the function returns <tt>Vector2(0, 0)</tt>.
158         - If the other object is exactly at my left, the function returns <tt>Vector2(-0.5, 0)</tt>.
159         - If the other object is exactly at my right, the function returns <tt>Vector2(0.5, 0)</tt>.
160         - If the other object is only a bit at my right, the function still returns <tt>Vector2(0.01, 0)</tt>.
161         - If the other object is exactly above me, the function returns <tt>Vector2(0, 0.5)</tt>.
162    */
163    orxonox::Vector2 get2DViewcoordinates(const orxonox::Vector3& myposition, const orxonox::Vector3& mydirection, const orxonox::Vector3& myorthonormal, const orxonox::Vector3& otherposition)
164    {
165        orxonox::Vector3 distance = otherposition - myposition;
166
167        // project difference vector on our plane
168        orxonox::Vector3 projection = Ogre::Plane(mydirection, myposition).projectVector(distance);
169
170        float projectionlength = projection.length();
171        if (projectionlength == 0)
172        {
173            if (myposition.dotProduct(otherposition) >= 0)
174                return orxonox::Vector2(0, 0);
175            else
176                return orxonox::Vector2(0, 1);
177        }
178        //float angle = acos(clamp<float>(myorthonormal.dotProduct(projection) / projectionlength, -1, 1));
179
180        float cos_value = clamp<float>(myorthonormal.dotProduct(projection) / projectionlength, -1, 1);
181        float sin_value = sqrt( 1 - cos_value*cos_value );
182
183        float distancelength = distance.length();
184        if (distancelength == 0) return orxonox::Vector2(0, 0);
185        float radius = acos(clamp<float>(mydirection.dotProduct(distance) / distancelength, -1, 1)) / math::pi;
186
187        if ((mydirection.crossProduct(myorthonormal)).dotProduct(distance) > 0)
188            return orxonox::Vector2( sin_value * radius, cos_value * radius);
189        else
190            return orxonox::Vector2( -sin_value * radius, cos_value * radius);
191    }
192
193
194    /**
195            @brief Gets the 2D project vector for the 3D Radar .
196            @param myposition My position
197            @param mydirection My viewing direction
198            @param myorthonormal My orthonormalvector (pointing upwards through my head)
199            @param otherposition The position of the other object
200            @param mapangle The angle you look on the 3Dmap
201            @param detectionlimit The limit in which objects are shown on the map
202            @return The viewing direction
203
204            Examples:
205             -
206    */
207    orxonox::Vector2 get3DProjection(const orxonox::Vector3& myposition, const orxonox::Vector3& mydirection, const orxonox::Vector3& myorthonormal, const orxonox::Vector3& otherposition, const float mapangle, const float detectionlimit)
208    {
209        // Orxonox Vectors: x_direction you are looking, y_direction points up, z_direction points to the right
210        orxonox::Vector3 distance = otherposition - myposition; // get vector from Ship to object
211
212        // new coordinate system:       x_axsis:        mydirection             (points front)
213        //                                                      y_axsis:        myorthonormal   (points up)
214        //                                                      z_axsis:        myside                  (points right)
215
216        orxonox::Vector3 myside = mydirection.crossProduct(myorthonormal); // get 3. base vector
217
218        distance = 4*distance / detectionlimit; // shrink vector on map
219        if(distance.length() > 1.0f) // if object would wander outside of the map
220                {
221                distance = distance / distance.length();
222                        }
223
224        // perform a coordinate transformation to get distance in relation of the position of the ship
225        orxonox::Vector3 distanceShip = getTransformedVector(distance, mydirection, myorthonormal, myside);
226
227        // calculate 2D vector on the map (with angle between x/z - plain and line of sight)
228        float xcoordinate = distanceShip.z; // z; cause x direction on screen is to the right side
229        float ycoordinate = distanceShip.x*sin(mapangle)+distanceShip.y*cos(mapangle);
230        return orxonox::Vector2(xcoordinate , ycoordinate);
231    }
232
233    /**
234               @brief Gets if a object is over the x/z - plain on map
235               @param myposition My position
236               @param mydirection My viewing direction
237               @param myorthonormal My orthonormalvector (pointing upwards through my head)
238               @param otherposition The position of the other object
239               @param mapangle The angle you look on the 3Dmap
240               @return If distancevector to the other object has a positive y-coordinate
241
242               Examples:
243                Returns true if object is over x/z - plain
244                Returns false if object is below x/z -plain
245    */
246    bool isObjectHigherThanShipOnMap(const orxonox::Vector3& myposition, const orxonox::Vector3& mydirection, const orxonox::Vector3& myorthonormal, const orxonox::Vector3& otherposition, const float mapangle)
247    {
248        // Orxonox Vectors: x_direction you are looking, y_direction points up, z_direction points to the right
249        orxonox::Vector3 distance = otherposition - myposition;
250
251        // new coordinate system:       x_axsis:        mydirection             (points front)
252        //                                                      y_axsis:        myorthonormal   (points up)
253        //                                                      z_axsis:        myside                  (points right)
254
255        orxonox::Vector3 myside = mydirection.crossProduct(myorthonormal); // get vector from Ship to object
256
257
258        // perform a coordinate transformation to get distance in relation of the position of the ship
259        orxonox::Vector3 distanceShip = getTransformedVector(distance, mydirection, myorthonormal, myside);
260
261        if(distanceShip.y >= 0)
262                return true;
263        else
264                return false;
265    }
266
267    /**
268                   @brief A value between 0 and 10, in order how other object is in front or in back
269                   @param myposition My position
270                   @param mydirection My viewing direction
271                   @param myorthonormal My orthonormalvector (pointing upwards through my head)
272                   @param otherposition The position of the other object
273                   @param detectionlimit The limit in which objects are shown on the map
274                   @return value between 0 and 100
275    */
276    int determineMap3DZOrder(const orxonox::Vector3& myposition, const orxonox::Vector3& mydirection, const orxonox::Vector3& myorthonormal, const orxonox::Vector3& otherposition, const float detectionlimit)
277    {
278        orxonox::Vector3 distance = otherposition - myposition; // get vector from Ship to object
279        orxonox::Vector3 myside = mydirection.crossProduct(myorthonormal);      // get vector to the side
280
281        distance = 4*distance / detectionlimit; // shrink vector on map
282        if(distance.length() > 1.0f) // if object would wander outside of the map
283        {
284                distance = distance / distance.length();
285        }
286
287        // perform a coordinate transformation to get distance in relation of the position of the ship
288        orxonox::Vector3 distanceShip = getTransformedVector(distance, mydirection, myorthonormal, myside);
289
290        return (int) 50 - 100*distanceShip.x;
291    }
292
293
294    /**
295                @brief Gets the new vector after a coordinate transformation
296                @param distance Vector which will be transformed
297                @param mydirection New x basevector
298                @param myorthonormal New y basevector
299                @param otherposition New z basevector
300                @return direction in the new coordinates
301
302                x is vector in old coordinates
303                y is vector in old coordinates
304                T is transform matrix with:
305                        T = (t1 , t2 , t3)
306                        t1 = mydirection
307                        t2 = myorthonormal
308                        t3 = myside
309
310                y = T^(-1)*x
311            */
312    orxonox::Vector3 getTransformedVector(const orxonox::Vector3& distance, const orxonox::Vector3& mydirection, const orxonox::Vector3& myorthonormal, const orxonox::Vector3& myside)
313    {
314        // inverse of the transform matrix
315        float determinant = +mydirection.x * (myorthonormal.y*myside.z - myside.y*myorthonormal.z)
316                                                -mydirection.y * (myorthonormal.x*myside.z - myorthonormal.z*myside.x)
317                                                +mydirection.z * (myorthonormal.x*myside.y - myorthonormal.y*myside.x);
318        float invdet = 1/determinant;
319
320        // transform matrix
321        orxonox::Vector3 xinvtransform;
322        orxonox::Vector3 yinvtransform;
323        orxonox::Vector3 zinvtransform;
324
325        xinvtransform.x = (myorthonormal.y * myside.z        - myside.y        * myorthonormal.z)*invdet;
326        xinvtransform.y = (mydirection.z   * myside.y        - mydirection.y   * myside.z       )*invdet;
327        xinvtransform.z = (mydirection.y   * myorthonormal.z - mydirection.z   * myorthonormal.y)*invdet;
328        yinvtransform.x = (myorthonormal.z * myside.x        - myorthonormal.x * myside.z       )*invdet;
329        yinvtransform.y = (mydirection.x   * myside.z        - mydirection.z   * myside.x       )*invdet;
330        yinvtransform.z = (myorthonormal.x * mydirection.z   - mydirection.x   * myorthonormal.z)*invdet;
331        zinvtransform.x = (myorthonormal.x * myside.y        - myside.x        * myorthonormal.y)*invdet;
332        zinvtransform.y = (myside.x        * mydirection.y   - mydirection.x   * myside.y       )*invdet;
333        zinvtransform.z = (mydirection.x   * myorthonormal.y - myorthonormal.x * mydirection.)*invdet;
334
335        // coordinate transformation
336        orxonox::Vector3 distanceShip;
337        distanceShip.x = xinvtransform.x * distance.x + yinvtransform.x * distance.y + zinvtransform.x * distance.z;
338        distanceShip.y = xinvtransform.y * distance.x + yinvtransform.y * distance.y + zinvtransform.y * distance.z;
339        distanceShip.z = xinvtransform.z * distance.x + yinvtransform.z * distance.y + zinvtransform.z * distance.z;
340
341        return distanceShip;
342    }
343
344    /**
345        @brief Returns the predicted position I have to aim at, if I want to hit a moving target with a moving projectile.
346        @param myposition My position
347        @param projectilespeed The speed of my projectile
348        @param targetposition The position of my target
349        @param targetvelocity The velocity of my target
350        @return The predicted position
351
352        The function predicts the position based on a linear velocity of the target. If the target changes speed or direction, the projectile will miss.
353    */
354    orxonox::Vector3 getPredictedPosition(const orxonox::Vector3& myposition, float projectilespeed, const orxonox::Vector3& targetposition, const orxonox::Vector3& targetvelocity)
355    {
356        float squaredProjectilespeed = projectilespeed * projectilespeed;
357        orxonox::Vector3 distance = targetposition - myposition;
358        float a = distance.squaredLength();
359        float b = 2 * (distance.x + distance.y + distance.z) * (targetvelocity.x + targetvelocity.y + targetvelocity.z);
360        float c = targetvelocity.squaredLength();
361
362        float temp = 4*squaredProjectilespeed*c + a*a - 4*b*c;
363        if (temp < 0)
364            return orxonox::Vector3::ZERO;
365
366        temp = sqrt(temp);
367        float time = (temp + a) / (2 * (squaredProjectilespeed - b));
368        return (targetposition + targetvelocity * time);
369    }
370
371    /**
372        @brief Returns a unique number. This function will never return the same value twice.
373    */
374    unsigned long getUniqueNumber()
375    {
376        static unsigned long aNumber = 135;
377        return aNumber++;
378    }
379
380
381    //////////////////////////
382    // Conversion functions //
383    //////////////////////////
384
385    // std::string to Vector2
386    bool ConverterFallback<std::string, orxonox::Vector2>::convert(orxonox::Vector2* output, const std::string& input)
387    {
388        size_t opening_parenthesis, closing_parenthesis = input.find('}');
389        if ((opening_parenthesis = input.find('{')) == std::string::npos)
390            opening_parenthesis = 0;
391        else
392            opening_parenthesis++;
393
394        SubString tokens(input.substr(opening_parenthesis, closing_parenthesis - opening_parenthesis),
395                         ",", SubString::WhiteSpaces, false, '\\', true, '"', true, '\0', '\0', true, '\0');
396        if (tokens.size() >= 2)
397        {
398            if (!convertValue(&(output->x), tokens[0]))
399                return false;
400            if (!convertValue(&(output->y), tokens[1]))
401                return false;
402
403            return true;
404        }
405        return false;
406    }
407
408    // std::string to Vector3
409    bool ConverterFallback<std::string, orxonox::Vector3>::convert(orxonox::Vector3* output, const std::string& input)
410    {
411        size_t opening_parenthesis, closing_parenthesis = input.find('}');
412        if ((opening_parenthesis = input.find('{')) == std::string::npos)
413            opening_parenthesis = 0;
414        else
415            opening_parenthesis++;
416
417        SubString tokens(input.substr(opening_parenthesis, closing_parenthesis - opening_parenthesis),
418                         ",", SubString::WhiteSpaces, false, '\\', true, '"', true, '\0', '\0', true, '\0');
419        if (tokens.size() >= 3)
420        {
421            if (!convertValue(&(output->x), tokens[0]))
422                return false;
423            if (!convertValue(&(output->y), tokens[1]))
424                return false;
425            if (!convertValue(&(output->z), tokens[2]))
426                return false;
427
428            return true;
429        }
430        return false;
431    }
432
433    // std::string to Vector4
434    bool ConverterFallback<std::string, orxonox::Vector4>::convert(orxonox::Vector4* output, const std::string& input)
435    {
436        size_t opening_parenthesis, closing_parenthesis = input.find('}');
437        if ((opening_parenthesis = input.find('{')) == std::string::npos)
438            opening_parenthesis = 0;
439        else
440            opening_parenthesis++;
441
442        SubString tokens(input.substr(opening_parenthesis, closing_parenthesis - opening_parenthesis),
443                         ",", SubString::WhiteSpaces, false, '\\', true, '"', true, '\0', '\0', true, '\0');
444        if (tokens.size() >= 4)
445        {
446            if (!convertValue(&(output->x), tokens[0]))
447                return false;
448            if (!convertValue(&(output->y), tokens[1]))
449                return false;
450            if (!convertValue(&(output->z), tokens[2]))
451                return false;
452            if (!convertValue(&(output->w), tokens[3]))
453                return false;
454
455            return true;
456        }
457        return false;
458    }
459
460    // std::string to Quaternion
461    bool ConverterFallback<std::string, orxonox::Quaternion>::convert(orxonox::Quaternion* output, const std::string& input)
462    {
463        size_t opening_parenthesis, closing_parenthesis = input.find('}');
464        if ((opening_parenthesis = input.find('{')) == std::string::npos)
465            opening_parenthesis = 0;
466        else
467            opening_parenthesis++;
468
469        SubString tokens(input.substr(opening_parenthesis, closing_parenthesis - opening_parenthesis), ",", SubString::WhiteSpaces, false, '\\', true, '"', true, '\0', '\0', true, '\0');
470        if (tokens.size() >= 4)
471        {
472            if (!convertValue(&(output->w), tokens[0]))
473                return false;
474            if (!convertValue(&(output->x), tokens[1]))
475                return false;
476            if (!convertValue(&(output->y), tokens[2]))
477                return false;
478            if (!convertValue(&(output->z), tokens[3]))
479                return false;
480
481            return true;
482        }
483        return false;
484    }
485
486    // std::string to ColourValue
487    bool ConverterFallback<std::string, orxonox::ColourValue>::convert(orxonox::ColourValue* output, const std::string& input)
488    {
489        size_t opening_parenthesis, closing_parenthesis = input.find('}');
490        if ((opening_parenthesis = input.find('{')) == std::string::npos)
491            opening_parenthesis = 0;
492        else
493            opening_parenthesis++;
494
495        SubString tokens(input.substr(opening_parenthesis, closing_parenthesis - opening_parenthesis), ",", SubString::WhiteSpaces, false, '\\', true, '"', true, '\0', '\0', true, '\0');
496        if (tokens.size() >= 3)
497        {
498            if (!convertValue(&(output->r), tokens[0]))
499                return false;
500            if (!convertValue(&(output->g), tokens[1]))
501                return false;
502            if (!convertValue(&(output->b), tokens[2]))
503                return false;
504            if (tokens.size() >= 4)
505            {
506                if (!convertValue(&(output->a), tokens[3]))
507                    return false;
508            }
509            else
510                output->a = 1.0;
511
512            return true;
513        }
514        return false;
515    }
516}
Note: See TracBrowser for help on using the repository browser.