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