geometry.cpp
author insilmaril
Thu, 25 Feb 2010 11:03:52 +0000
changeset 824 36eb4b8f409e
parent 798 d251c7b2de54
child 835 31841b366d5e
permissions -rw-r--r--
Added dialog for HTML export. Grouping in Switchboard shortcuts
     1 #include "geometry.h"
     2 
     3 #include <math.h>
     4 #include "misc.h"
     5 
     6 #include <QString>
     7 
     8 #include <iostream>
     9 using namespace std;
    10 
    11 
    12 QRectF addBBox(QRectF r1, QRectF r2)
    13 {	
    14 	// Find smallest QRectF containing given rectangles
    15 
    16 	QRectF n;
    17 	// Set left border
    18 	if (r1.left() <= r2.left() )
    19 		n.setLeft(r1.left() );
    20 	else
    21 		n.setLeft(r2.left() );
    22 		
    23 	// Set top border		
    24 	if (r1.top() <= r2.top() )
    25 		n.setTop(r1.top() );
    26 	else
    27 		n.setTop(r2.top() );
    28 		
    29 	// Set right border
    30 	if (r1.right() <= r2.right() )
    31 		n.setRight(r2.right() );
    32 	else
    33 		n.setRight(r1.right() );
    34 		
    35 	// Set bottom 
    36 	if (r1.bottom() <= r2.bottom() )
    37 		n.setBottom(r2.bottom() );
    38 	else
    39 		n.setBottom(r1.bottom() );
    40 	return n;
    41 }
    42 
    43 bool isInBox(const QPointF &p, const QRectF &box)
    44 {
    45     if (p.x() >= box.left() && p.x() <= box.right()  
    46 	&& p.y() <= box.bottom() && p.y() >= box.top() )
    47 		return true;
    48     return false;	
    49 }
    50 
    51 qreal distance (const QPointF &p, const QPointF &q)
    52 {
    53 	return sqrt (p.x()*q.x() + p.y()*q.y());
    54 }
    55 
    56 Vector::Vector ():QPointF ()
    57 {
    58 }
    59 
    60 Vector::Vector (const QPointF &p):QPointF (p)
    61 {
    62 }
    63 
    64 Vector::Vector (qreal x, qreal y):QPointF (x,y)
    65 {
    66 }
    67 
    68 //! Normalize vector
    69 void Vector::normalize ()
    70 {
    71 	if (x()==0 && y()==0) return;
    72 	qreal l=sqrt ( x()*x() + y()*y() );
    73 	setX (x()/l);
    74 	setY (y()/l);
    75 }
    76 
    77 //! Dot product of two vectors
    78 qreal Vector::dotProduct (const QPointF &b)
    79 {
    80 	return x()*b.x() + y()*b.y();
    81 }
    82 
    83 
    84 void Vector::scale (const qreal &f)
    85 {
    86 	setX (x()*f);
    87 	setY (y()*f);
    88 }
    89 
    90 void Vector::invert ()
    91 {
    92 	setX (-x());
    93 	setY (-y());
    94 }
    95 
    96 QPointF Vector::toQPointF ()
    97 {
    98 	return QPointF (x(),y());
    99 }
   100 
   101 /*! Calculate the projection of a polygon on an axis
   102     and returns it as a [min, max] interval  */
   103 ConvexPolygon::ConvexPolygon ()
   104 {
   105 }
   106 
   107 ConvexPolygon::ConvexPolygon (QPolygonF p):QPolygonF (p)
   108 {
   109 }
   110 
   111 void ConvexPolygon::calcCentroid() 
   112 {
   113 	// Calculate area and centroid
   114 	// http://en.wikipedia.org/wiki/Centroid
   115 	qreal cx,cy,p;
   116 	cx=cy=0;
   117 	_area=0;
   118 
   119 	append (at(0));
   120 	for (int i=0;i<size()-1;i++)
   121 	{
   122 		p=at(i).x() * at(i+1).y() - at(i+1).x() * at(i).y();
   123 		_area+=p;
   124 		cx+=(at(i).x()+at(i+1).x()) * p;
   125 		cy+=(at(i).y()+at(i+1).y()) * p;
   126 	}	
   127 	pop_back();
   128 	// area is negative if vertices ordered counterclockwise
   129 	// (in mirrored graphicsview!)
   130 	_area=_area/2;	
   131 	p=_area*6;
   132 	_centroid.setX (cx/p);
   133 	_centroid.setY (cy/p);
   134 }
   135 
   136 QPointF ConvexPolygon::centroid() const
   137 {
   138 	return _centroid;
   139 }
   140 
   141 qreal ConvexPolygon::weight() const
   142 {
   143 	return _area;
   144 }
   145 
   146 std::string ConvexPolygon::toStdString()
   147 {
   148 	QString s ("(");
   149 	for (int i=0;i<size();++i)
   150 	{
   151 		s+=QString("(%1,%2)").arg(at(i).x()).arg(at(i).y());
   152 		if (i<size()-1) s+=",";
   153 	}
   154 	s+=")";	
   155 	return s.toStdString();
   156 }
   157 
   158 Vector ConvexPolygon::at(const int &i) const
   159 {
   160 	return Vector (QPolygonF::at(i).x(),QPolygonF::at(i).y());
   161 }
   162 
   163 void ConvexPolygon::translate ( const Vector & offset )
   164 { translate (offset.x(),offset.y());}
   165 
   166 void ConvexPolygon::translate ( qreal dx, qreal dy )
   167 {
   168 	QPolygonF::translate (dx,dy);
   169 	_centroid=_centroid+QPointF (dx,dy);
   170 }
   171 
   172 void projectPolygon(Vector axis, ConvexPolygon polygon, qreal &min, qreal &max) 
   173 {
   174     // To project a point on an axis use the dot product
   175 
   176 	//cout << "Projecting on "<< axis<<endl;
   177     qreal d = axis.dotProduct(polygon.at(0));
   178     min = d;
   179     max = d;
   180     for (int i = 0; i < polygon.size(); i++) 
   181 	{
   182         d= polygon.at(i).dotProduct (axis);
   183         if (d < min) 
   184             min = d;
   185         else 
   186             if (d> max) max = d;
   187 	//	cout << "p="<<polygon.at(i)<<"  d="<<d<<"  (min, max)=("<<min<<","<<max<<")\n";	
   188     }
   189 }
   190 
   191 // Calculate the signed distance between [minA, maxA] and [minB, maxB]
   192 // The distance will be negative if the intervals overlap
   193 
   194 qreal intervalDistance(qreal minA, qreal maxA, qreal minB, qreal maxB) {
   195     if (minA < minB) {
   196         return minB - maxA;
   197     } else {
   198         return minA - maxB;
   199     }
   200 }
   201 
   202 /*!
   203  Check if polygon A is going to collide with polygon B.
   204  The last parameter is the *relative* velocity 
   205  of the polygons (i.e. velocityA - velocityB)
   206 */
   207 
   208 PolygonCollisionResult polygonCollision(ConvexPolygon polygonA, 
   209                               ConvexPolygon polygonB, Vector velocity) 
   210 {
   211     PolygonCollisionResult result;
   212     result.intersect = true;
   213     result.willIntersect = true;
   214 
   215     int edgeCountA = polygonA.size();
   216     int edgeCountB = polygonB.size();
   217     qreal minIntervalDistance = 1000000000;
   218     QPointF translationAxis;
   219     QPointF edge;
   220 
   221 /*
   222 	cout << "\nA: ";
   223 	for (int k=0; k<edgeCountA;k++)
   224 		cout <<polygonA.at(k);
   225 	cout << "\nB: ";
   226 	for (int k=0; k<edgeCountB;k++)
   227 		cout <<polygonB.at(k);
   228 	cout <<endl;	
   229 */		
   230 		
   231     // Loop through all the edges of both polygons
   232 	for (int i=0;i<edgeCountA + edgeCountB;i++)
   233 	{
   234         if (i< edgeCountA) 
   235 		{
   236 			// Loop through polygon A
   237 			if (i<edgeCountA-1)
   238 				edge = QPointF (
   239 					polygonA.at(i+1).x()-polygonA.at(i).x(), 
   240 					polygonA.at(i+1).y()-polygonA.at(i).y());
   241 			else		
   242 				edge = QPointF (
   243 					polygonA.at(0).x()-polygonA.at(i).x(), 
   244 					polygonA.at(0).y()-polygonA.at(i).y());
   245         } else 
   246 		{
   247 			// Loop through polygon B
   248 			if (i < edgeCountA +edgeCountB -1 )
   249 				edge = QPointF (
   250 					polygonB.at(i-edgeCountA+1).x() - polygonB.at(i-edgeCountA).x(), 
   251 					polygonB.at(i-edgeCountA+1).y() - polygonB.at(i-edgeCountA).y());
   252 			else	
   253 				edge = QPointF (
   254 					polygonB.at(0).x() - polygonB.at(i-edgeCountA).x(), 
   255 					polygonB.at(0).y() - polygonB.at(i-edgeCountA).y());
   256 		}
   257 
   258         // ===== 1. Find if the polygons are currently intersecting =====
   259 
   260         // Find the axis perpendicular to the current edge
   261 
   262         Vector axis (-edge.y(), edge.x());
   263         axis.normalize();
   264 
   265         // Find the projection of the polygon on the current axis
   266 
   267         qreal minA = 0; qreal minB = 0; qreal maxA = 0; qreal maxB = 0;
   268         projectPolygon(axis, polygonA, minA, maxA);
   269         projectPolygon(axis, polygonB, minB, maxB);
   270 
   271         // Check if the polygon projections are currentlty intersecting
   272 
   273         qreal d = intervalDistance(minA, maxA, minB, maxB);
   274         if (d > 0) result.intersect = false;
   275 
   276        // ===== 2. Now find if the polygons *will* intersect =====
   277 
   278 
   279         // Project the velocity on the current axis
   280 
   281         qreal velocityProjection = axis.dotProduct(velocity);
   282 
   283         // Get the projection of polygon A during the movement
   284 
   285         if (velocityProjection < 0) 
   286             minA += velocityProjection;
   287         else 
   288             maxA += velocityProjection;
   289 
   290         // Do the same test as above for the new projection
   291 
   292         // d = intervalDistance(minA, maxA, minB, maxB);
   293         //if (d > 0) result.willIntersect = false;
   294 		/*
   295 		cout <<"   ";
   296 		cout << "edge="<<edge<<"  ";
   297 		cout <<"axis="<<axis<<"  ";
   298 		cout <<"dA=("<<minA<<","<<maxA<<")  dB=("<<minB<<","<<maxB<<")";
   299 		cout <<"  d="<<d<<"   ";
   300 		//cout <<"minD="<<minIntervalDistance<<"  ";
   301 		cout <<"int="<<result.intersect<<"  ";
   302 		//cout <<"wint="<<result.willIntersect<<"  ";
   303 		//cout <<"velProj="<<velocityProjection<<"  ";
   304 		cout <<endl;
   305 		*/
   306 	
   307         if (result.intersect )// || result.willIntersect) 
   308 		{
   309 			// Check if the current interval distance is the minimum one. If so
   310 			// store the interval distance and the current distance.  This will
   311 			// be used to calculate the minimum translation vector
   312 
   313 			if (d<0) d=-d;
   314 			if (d < minIntervalDistance) {
   315 				minIntervalDistance = d;
   316 				//translationAxis = axis;
   317 				//cout << "tAxix="<<translationAxis<<endl;
   318 
   319 				//QPointF t = polygonA.Center - polygonB.Center;
   320 				//QPointF t = polygonA.at(0) - polygonB.at(0);
   321 				//if (dotProduct(t,translationAxis) < 0)
   322 				//	translationAxis = -translationAxis;
   323 			}
   324 		}
   325     }
   326 
   327     // The minimum translation vector
   328     // can be used to push the polygons appart.
   329 
   330     if (result.willIntersect)
   331         result.minTranslation = 
   332                translationAxis * minIntervalDistance;
   333     
   334     return result;
   335 }
   336 
   337 /* The function can be used this way: 
   338    QPointF polygonATranslation = new QPointF();
   339 */   
   340 
   341 
   342 /*
   343 PolygonCollisionResult r = PolygonCollision(polygonA, polygonB, velocity);
   344 
   345 if (r.WillIntersect) 
   346   // Move the polygon by its velocity, then move
   347   // the polygons appart using the Minimum Translation Vector
   348   polygonATranslation = velocity + r.minTranslation;
   349 else 
   350   // Just move the polygon by its velocity
   351   polygonATranslation = velocity;
   352 
   353 polygonA.Offset(polygonATranslation);
   354 
   355 */
   356 
   357